Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That really depends.

Pegging your fixed timestep engine to rAF could have the consequence of dropping frames when you have a large gap between two frames and enough physics frames get called at once that the next rAF window gets missed. If your performance is bounded by the physics simulation, you could potentially trigger a spiral of death and never catch up.

Of course there are ways to mitigate this, but that just further complicates things.

You have the right idea, adding each frame delta to an accumulator and triggering a physics step when reaches the appropriate value, however rAF is not the answer because it can create a potentially infinite frame delta.

It's usually best to not peg your fixed-timestep physics to rAF or at the very least, pause the game entirely when the window isn't focused.



Damn, you're right, it's more complicated than I thought. But what else would you use? setInterval suffers from the same problem, doesn't it?


That's a good question. setInterval definitely also has its strengths and weaknesses, but it does beat rAF() here in that you can guarantee at least one frame will be ran every X milliseconds.

With regards to Javascript physics engines, I'm only versed with Matter.js.

Matter.js's Engine.update() takes a frame delta as an argument and uses Verlet integration [0] to make things work under the hood. You can optionally calculate a correction factor to be applied each frame in order to smooth out calculations with janky framerates, but if you can maintain constant FPS then it's not an issue.

Unfortunately, rAF() once again becomes a pain because of the lack of proper control over FPS capping, so monitors with higher refresh rates have a larger window for variable frame deltas. I'm hopeful that these shortcomings will eventually be addressed in the spec.

[0] https://lonesock.net/article/verlet.html




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: