TExcelTAD

Delta Time

Frames don't all take the same time. One player's monitor runs at 60 Hz, another at 144 Hz; a loading hitch can make one frame take 100 ms. Delta time (deltaTime, dt) is the time that passed since the previous frame, in seconds. Multiplying movement by it makes the game run at the same speed no matter how many frames per second the machine draws.

The bug it fixes

Move an object "2 pixels per frame" and its speed depends on the frame rate. Simulate one second of play on three machines:

csharp · try it yourself
using System;

foreach (int fps in new[] { 30, 60, 144 })
{
    double x = 0;
    for (int frame = 0; frame < fps; frame++)   // one second of frames
        x += 2;                                   // 2 units per FRAME
    Console.WriteLine(
quot;{fps,3} FPS: moved {x} units in one second"); }
 30 FPS: moved 60 units in one second
 60 FPS: moved 120 units in one second
144 FPS: moved 288 units in one second

On the 144 Hz monitor the character is almost five times faster than on a 30 FPS laptop. Older games really shipped with this bug; some console ports ran faster in 60 Hz regions than in 50 Hz ones.

Speed × delta time

Express speeds per second and multiply by dt every frame:

csharp · try it yourself
using System;

const double speed = 120;   // units per SECOND

foreach (int fps in new[] { 30, 60, 144 })
{
    double dt = 1.0 / fps;
    double x = 0;
    for (int frame = 0; frame < fps; frame++)
        x += speed * dt;
    Console.WriteLine(
quot;{fps,3} FPS: dt={dt * 1000:F2} ms, moved {x:F2} units"); }
 30 FPS: dt=33.33 ms, moved 120.00 units
 60 FPS: dt=16.67 ms, moved 120.00 units
144 FPS: dt=6.94 ms, moved 120.00 units

The same rule applies to everything that changes over time: rotation (degrees per second), timers (cooldown -= dt), spawn rates and animation. In engines:

Engine Where dt comes from
Unity Time.deltaTime inside Update()
Godot the delta parameter of _process(delta)
Unreal the DeltaTime parameter of Tick(float DeltaTime)
Browser difference between two requestAnimationFrame timestamps (milliseconds, so divide by 1000)

Timers with delta time

A cooldown is just a number counting down by dt. Here frames arrive at uneven intervals, as they do in real games, and the ability becomes ready after 0.5 s of game time regardless:

csharp · try it yourself
using System;

double[] frameTimes = { 0.016, 0.017, 0.100, 0.016, 0.033, 0.016, 0.200, 0.016, 0.016, 0.100 };
double cooldown = 0.5;   // seconds until the dash is ready
double clock = 0;

foreach (double dt in frameTimes)
{
    clock += dt;
    cooldown -= dt;
    string state = cooldown <= 0 ? "READY" : 
quot;{cooldown:F3} s left"; Console.WriteLine(
quot;t={clock:F3} dt={dt:F3} dash: {state}"); }
t=0.016  dt=0.016  dash: 0.484 s left
t=0.033  dt=0.017  dash: 0.467 s left
t=0.133  dt=0.100  dash: 0.367 s left
t=0.149  dt=0.016  dash: 0.351 s left
t=0.182  dt=0.033  dash: 0.318 s left
t=0.198  dt=0.016  dash: 0.302 s left
t=0.398  dt=0.200  dash: 0.102 s left
t=0.414  dt=0.016  dash: 0.086 s left
t=0.430  dt=0.016  dash: 0.070 s left
t=0.530  dt=0.100  dash: READY

Where variable delta time hurts

dt scaling is right for most gameplay, but a very large dt causes trouble:

  • Tunneling: a bullet that moves 2000 units/s jumps 400 units in a 200 ms hitch and passes straight through a wall without ever overlapping it.
  • Unstable physics: springs and stacks of objects explode when the step is too big.
  • Different results on different machines: x += v * dt; v += g * dt; gives slightly different jump heights at 30 and 144 FPS, because the arc is sampled differently.

Engines limit the first problem by clamping dt (Unity caps it with Time.maximumDeltaTime; the canvas example in the previous lesson used Math.min(dt, 0.1)). The real fix for physics and determinism is a fixed timestep, the topic of the next lesson.

Smoothing that respects dt

A common trick is to move a camera a fraction of the way to its target each frame: x = lerp(x, target, 0.1). That fraction is per frame, so the camera is faster on fast machines. The frame-rate-independent version uses an exponential:

js · try it yourself
const lerp = (a, b, t) => a + (b - a) * t;

function follow(fps, smoothing) {
  const dt = 1 / fps;
  let naive = 0, damped = 0;
  for (let i = 0; i < fps / 2; i++) {             // half a second
    naive = lerp(naive, 100, 0.1);                 // 10% per frame
    damped = lerp(damped, 100, 1 - Math.exp(-smoothing * dt));
  }
  console.log(`${String(fps).padStart(3)} FPS  naive: ${naive.toFixed(1).padStart(5)}  damped: ${damped.toFixed(1)}`);
}
follow(30, 4);
follow(60, 4);
follow(120, 4);
 30 FPS  naive:  79.4  damped: 86.5
 60 FPS  naive:  95.8  damped: 86.5
120 FPS  naive:  99.8  damped: 86.5

After half a second the naive camera has covered 79% of the distance at 30 FPS but almost all of it at 120 FPS. The damped camera is at 86.5% on every machine, because 1 - exp(-k * dt) compounds to the same total however the time is sliced. Math for Games covers interpolation in depth.

Test yourself

A character moves x += 5 every frame. What happens on a 120 Hz monitor compared to 60 Hz?

  1. Same speed
  2. Twice as fast
  3. Half as fast
  4. It depends on the GPU

In which unit is Unity's Time.deltaTime?

  1. Milliseconds
  2. Seconds
  3. Frames
  4. Ticks

Why is lerp(x, target, 0.1) every frame not frame-rate independent?

  1. lerp is slow
  2. The 0.1 is a fraction per frame, so more frames move it further per second
  3. It uses integers
  4. It is, if you clamp dt