I'm developing a Javascript based multiplayer game. So far I have the basic server, client and networking ready.
I did have an issue where my player was moving faster on a 120Hz screen as opposed to a 60Hz screen. I've fixed this by multiplying the player's movementspeed by the deltatime of the 'requestAnimationFrame'.
However; would it be a better solution to separate the animations from the logic?
As in:
//Game loop; Do each 1/60th of a second
setInterval(gameTick, 1000/60);
function gameTick(){
player.handleKeys();
enemies.foreach( (enemy) => {
enemy.update();
});
}
//Draw loop; match to player screen refresh rate
window.requestAnimationFrame(gameLoop);
function gameLoop() {
player.draw();
enemies.foreach( (enemy) => {
enemy.draw();
});
window.requestAnimationFrame(gameLoop);
}
While the difference may be "neglectable" I want to avoid players with 240Hz 'spamming' the server and have an advantage over other players.
Though on the other hand for a 240Hz monitor; only 1 in 4 frames your keyboard input will be handled, so it may not feel as smooth?
This reason I'm asking is that this will be a competetive game and should thus be balanced. But I've checked various sources on which the consensus seems to be to use requestAnimationFrame (even for the logic; not only the drawing), though I'm doubting this and would like to know which is correct (and/or used in professional competetive games).
setInterval
is, again, not that reliable for actually timing something. Since its sharing the thread (which yourrequestAnimationFrame
does as well), it could still be slowed down if the computer isn't fast enough to do everything you want in a single loop. My guess would be to actually try to create a web worker that your main thread continuously updates and that has its own - very light - interval in a separate thread that exchanges data with your user and your server in a more predictable way. But that is really a guess, I have no diirect experience building this. – Bathymetry