1

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?

El Poisen
  • 121
  • 1
  • 8

1 Answers1

3

I would use the following logic :

  • before.update hook on your collection to update the status to Started using collection hooks
  • 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

Victor
  • 767
  • 4
  • 17
  • Hi Victor, thanks a lot for your reply ! So if i understand correctly, I should display the timer by using the defined date that I can maybe store im the game collection? Also should I write the Meteor.setTimeout in the before update hook? I have an error saying that its not possible to use timer in simulations. – El Poisen Jan 08 '18 at 10:30
  • 1
    @ElPoisen, I edited my answer with more code examples and details – Victor Jan 08 '18 at 14:47
  • Hey, thanks so much for taking the time I appreciate ! I think i get it now. – El Poisen Jan 08 '18 at 15:11