I'm currently developping a simple realtime multiplayer game and i'm stuck with the timer logic.
When there are enough players in a game, the status of the game is set to "STARTED" and from there i want to start a 10 seconds timer and show it to all the clients.
My idea is to use collection hooks and call a setTimeout after the collection update. But I don't really know how to do it and if it is the best solution.
Also maybe should I use cron instead of timers?
I would use the following logic :
set a datetime in the hook for the date when players were enough => save this data in your Game Collection
Game.before.update(function (userId, doc, fieldNames, modifier, options) {
if (modifier && modifier.$set && modifier.$set.nb_of_players > 10) {
modifier.$set.status = "Started";
modifier.$set.startingTime = new Date();
}
});
use a helper to compute dynamically the time to show on your client, here a basic working example of reactive time display, that you need to improve to get a countdown:
Template.Home.helpers({
time: function () {
return Template.instance().date.get();
},
});
Template.Home.onCreated(function () {
var self = Template.instance();
self.date = new ReactiveVar();
Meteor.setInterval(function () {
self.date.set(new Date());
}, 1);
});
use a setTimeout to actually do something 10 seconds later - this should be called after setting the game to started. Either in an autorun checking the value, or in the callback function of the Meteor.call you use :
Meteor.setTimeout(function(){
Meteor.call("launchAction", {data:data}, function (error, result) {
if (error){
console.error(error);
} else {
}
});
}, 10);
I also recommend using momentjs to actually manipulate dates and times