I've made a game that has gameticks every 1/60 seconds. These gameticks take very little time to calculate (< 0.5 ms).
The game is written in Javascript and uses requestAnimationFrame (rAF). rAF fires roughly a few milliseconds (how many is determined by what the browser thinks is necessary) before (mostly) every frame output to the monitor.
The code does the following every rAF:
- get a timestamp
- figure out how many gameticks should have happened at that timestamp, and (if needed) run enough to catch up
- render state after latest gametick to screen
This works fine most of the time. It runs at a consistent 60 gameticks/second, regardless of what the screen is doing (good for syncing multiplayer). It handles any framerate. The game looks smooth except, sometimes, the timestamps happen to be right around the boundary for new gameticks.
frame 10: gametick 2.01 (renders gametick 2)
frame 11: gametick 2.99 (renders gametick 2)
frame 12: gametick 4.01 (renders gametick 4)
frame 13: gametick 4.99 (renders gametick 4)
frame 14: gametick 6.01 (renders gametick 6)
When this happens, it stutters horribly. How do I make it avoid stuttering needlessly?