Fixed-timestep game loop for browser games
game-loopphysicsrequestanimationframejavascriptcanvasdeterminismflamedart
A browser game should run physics at a fixed rate and render at whatever rate requestAnimationFrame
delivers. The Spacebar JS rebuild settled on the following loop and constants after measuring and
fixing several real bugs.
The loop
- Fixed 60 Hz physics accumulator: add the real elapsed time to an accumulator and run
step(1/60)while the accumulator holds at least one step. - Step cap (MAX_STEPS = 5): the spiral-of-death guard. If the tab was slow, run at most 5 steps and drop the remaining time rather than trying to catch up forever.
- dt clamp of 0.25 s: a backgrounded tab returns with a huge dt; clamp it before it reaches the accumulator.
- Start the clock before the first rAF, not inside it, or the first frame sees a bogus elapsed time.
- Render once per rAF after the physics steps.
- Snap the camera to whole device pixels (multiply by
devicePixelRatio, round, divide) so tile edges and thin lines do not shimmer as the camera moves.
Units
Pick a fixed world scale and write it down. Spacebar uses 10 px = 1 m; the player tops out at 550 px/s (198 km/h) with acceleration 220 and a collider radius of 13 px. Its earlier Flutter build had three conflicting speed scales; unifying them on one definition ("KPH" = px/s x 3.6) required scaling every threshold so behavior stayed identical. Decide units once.
Contact resolution
When resolving a circle against multiple solids, take the deepest contact, not the first one found, and treat out-of-bounds as solid. See Tile collision with merged rectangles.
Gotchas
- Headless Chrome's
--virtual-time-budgetthrottles rAF, so a test can make a working rAF-gated loop look dead. See Headless Chrome testing gotchas.
Render interpolation and input frames
- After the physics steps,
alpha = accumulator / FIXED_DTand renderlerp(prevState, state, alpha); this keeps motion smooth when the display rate is not a multiple of the step rate (120 Hz phones, 144 Hz monitors). - Sample input once per tick into an
InputFrame. That is what makes input-replay ghosts, deterministic tests, and server-side run verification possible. - At a 120 Hz step and a 1200 px/s terminal velocity, one step moves 10 px, safely inside a 32 px platform, which also removes most tunneling (Collision tunneling (fast objects passing through walls)).
Bug classes caused by variable dt (found in Run, Flutter/Flame, 2026-10 audit)
Run (Justin's Flutter/Flame speedrun platformer) advanced physics by the raw frame delta. The
October 2026 architecture audit (tldr post #1769) found these recurring bugs:
- Frame-count constants: motionDelta.x * 60 to turn a per-frame delta into px/s, a
riding cooldown of 10 frames, a dimension-switch cooldown of 5 frames. All wrong off
60 fps; moving-platform velocity inheritance broke on high-refresh screens. Express
everything in seconds or fixed ticks.
- Wall-clock timers in gameplay: Timer / Future.delayed for respawn delays and
freezes keep running while the game is paused and race with restarts. Count down in
update(dt) on game time instead (Run's DeathManager moved to this in v0.8.85).
- Mismatched clocks: the run timer used raw dt while physics used clamped dt, so the
displayed time and the simulated time diverged.
- Movers not reset on respawn: moving platforms kept their phase across deaths, so every
attempt got a different, luck-dependent cycle. Reset movers to phase 0 on respawn (Run
v0.8.86 PathMotion.resetMotion()). Fair retries need a deterministic world.
- Aggressive dt clamping as a tunneling fix (20 ms cap) made the game floaty at low frame
rates. Clamp only pathological spikes (backgrounded tabs, as above).
Determinism limits in Dart
Dart cannot guarantee identical floating-point results across the VM, JS (web) and WASM, so even a fixed step will not replay inputs bit-exactly across platforms. That is why Run's ghosts record state at 10 Hz rather than inputs (Ghost replays for racing and speedrun games). Within one platform and build, fixed step + per-tick input + tick-counted delays is enough for deterministic tests and replays; stamp a physics version on recorded runs before changing the step.
Engine interaction (Flame)
Flame runs collision detection once per frame after all update() calls, so looping the step
inside update() does not give collisions between substeps. A real fixed step in Flame needs
its own pure-Dart collision pass (the audit's proposed sim/ layer with one
moveAndCollide), with Flame only rendering. See Flame engine architecture and gotchas.
See also
- Zero-allocation render and update loops
- Tile collision with merged rectangles
- Platformer movement feel (coyote time, jump buffering, wall jumps)
- Collision tunneling (fast objects passing through walls)
Linked from
- Arcade game design toolkit (loops, enemies, scoring, structure)
- Collision tunneling (fast objects passing through walls)
- Flame engine architecture and gotchas
- Flutter and Dart gotchas (collections, widgets, theming)
- Ghost replays for racing and speedrun games
- Platformer movement feel (coyote time, jump buffering, wall jumps)
- Run (runrunrunrun.run), Justin's speedrun platformer
- Sonic-style loop-the-loop physics
- Speedrun timers, medals, leaderboards, and anti-cheat
- Tile collision with merged rectangles
- Zero-allocation render and update loops