geckosio / phaser-on-nodejs

Allows you to run Phaser 3 game (including Phaser's physics engines) on Node.js
MIT License
103 stars 11 forks source link

Server animation frame timing schedule #2

Closed davidmball closed 4 years ago

davidmball commented 5 years ago

I noticed that server and client clocks were quickly becoming desynced. I think the issue is that in the animation frame the delay is added on rather than measured against a fixed time schedule. I'd suggest changing it to something like this:

var time = Date.now();

var animationFrame = function (cb) {
    if (typeof cb !== 'function')
        return 0; // this line saves a lot of cpu

    var next_time = time + 1000 / 60;
    var delay = next_time - Date.now();
    time = next_time;
    window.setTimeout(function () { return cb(0); }, delay);
    return 0;
};

Additionally this assume 60Hz although this is a configurable parameter for Phaser io.

yandeu commented 5 years ago

Thanks. I will try it and maybe add it if it work well :)

Do you think I should add a parameter to choose the frame rate?

davidmball commented 5 years ago

I'm not sure exactly how the frame rate should be configured for Phaser io as there are render, physics, etc frame rates. Perhaps as this is headless for a server it doesn't matter.

yandeu commented 5 years ago

Perhaps as this is headless for a server it doesn't matter.

That's what I thought while making it. The client and the server are 100% separated. The frame rate of the server does not really have an impact of the clients frame rate, nor does it have an impact on how many time the servers sends an update to the client.

davidmball commented 5 years ago

EDIT: Just noticed that you were talking about the frame rate. This part seems to be working for me and probably most people use 60 fps anyway. The matter physics engine used by phaser io seems to take the same step size regardless of fps anyway.

I noticed this when I was trying to synchronise matter physics across the client and server. The update steps on the server was slower than the client, and the matter physics engine takes fixed steps with each update loop. These update loops will be slower on the server.

yandeu commented 4 years ago

I have added the option to adjust the fps.