简体   繁体   中英

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 (eg 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);
}

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!

Although I don't work with games, there is a better alternative than setInterval, as shown here . It worked well for me in a business application. I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM