Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: alternative to setInterval which is more precise for game loop

My setup is a multiplayer game, with sockets to async transfer data.

Now because of the nature of a game, I have a game loop which should tick every 500ms to do player updating (e.g. position, appearance,...).

var self = this;

this.gameLoop = setInterval(function()
{   
    for (var i = 0; i < playerSize; i++)
    {
        self.players.get(i).update();
    };
}, 500);

I'm currently using setInterval but when i did some benchmarks with about 200 connections, setInterval drifted away to 1000ms instead of 500ms, which makes the whole game appear laggy. Also it's not accurate enough unfortunately with a little amount of players. (note that the update calls only take about 100ms maximum)

So to me after researching, there seems to be no other option then to spawn a process which only handles the timining mechanism? Or are there other options?

Anyone has done this before or can give some fundamental ideas/solutions on how to do this?

Full code:

Game.prototype.start = function()
{
    var average = 0;
    var cycles = 10;
    var prev = Date.now();

    this.thread = setInterval(function()
    {       
        console.log("interval time="+(Date.now() - prev));
        prev = Date.now();

        var s = Date.now();

        // EXECUTE UPDATES
    for (var i = 0; i < playerSize; i++)
    {
        self.players.get(i).update();
    };

        average += (Date.now() - s);

        cycles--;
        if(cycles == 0)
        {
            console.log("average update time: " + (average/10) + "ms");
            average = 0;
                cycles = 10;
            }
    }, 500);
}
like image 300
Captain Obvious Avatar asked Sep 15 '15 13:09

Captain Obvious


1 Answers

Here is an article on creating an accurate node.js game loop using a combination of setTimeout() and setImmediate so things are accurate but don't use up too much CPU.

The nanoTimer timing library might work for you. From the readme it sounds like it uses a similar approach. I don't know if it's been designed with games in mind but it should be worth a try!

like image 123
Sly_cardinal Avatar answered Sep 20 '22 05:09

Sly_cardinal