Delta Time
A tester reports that the drone in Harbour Hopper zips across the harbour on their gaming PC but crawls on an old phone. Same code, same level. The code moves the drone a fixed amount every frame, and the two machines don't manage the same number of frames per second.
The rule
Move by speed × delta time, never by a fixed amount per frame.
Delta time, usually written dt, is the number of seconds since the previous frame. At 60 fps it is about 0.0167 s; at 30 fps, about 0.0333 s. Multiply every rate by it:
DRONE_SPEED = 6.0 # metres per second
x += DRONE_SPEED * dt # metres this frameThe units prove it's right: metres per second × seconds = metres. A fast machine takes many small steps, a slow machine takes fewer big ones, and after one second both drones have flown 6 m.
The same rule covers everything that changes over time:
- turning:
angle += 90 * dtturns 90 degrees per second; - timers:
cooldown -= dtcounts down real seconds; - velocity itself:
velocity += acceleration * dt, which the Dynamics section builds on.
The shortcut
Read the units of every line that changes something over time. If a "per second" rate is multiplied by dt, the line is frame-rate independent. If a bare number is added every frame, as in x += 0.1, its real speed depends on the frame rate. Work out what it becomes at 30 fps and at 144 fps, and the bug jumps out.
The rate
The drone flies at 6 m/s.
Two traps are worth naming. The first is timers counted in frames: a "90-frame" cooldown lasts 1.5 s at 60 fps but 3 s at 30 fps. The second is a huge dt: if the player drags the window and one frame takes 2 seconds, x += speed * dt teleports the drone 12 m, possibly straight through a wall. Many games clamp dt to a maximum, such as 0.1 s, so one freak frame can't break the world.
Drills
Answer fast — trust the rule.
The movement code is x += 0.1 every frame. How fast does the drone fly on a 144 fps screen?
A crate-drop cooldown is written as 90 frames. How long does it last on a phone running at 30 fps?
One frame takes 2 seconds because the window was dragged. What does an unguarded x += 6 * dt do?
Which line is frame-rate independent?
Remember
- Move by speed ×
dt: a per-second rate times seconds gives this frame's amount. - Check the units; a bare number added every frame is a frame-rate bug.
- Count timers in seconds, not frames, and clamp a giant
dt.
