TExcelTAD
Home › Calculus Essentials › Physics Integration in Game Loops

Physics Integration in Game Loops

Every frame, a game engine has to answer one question: given positions, velocities and forces now, where is everything a fraction of a second later? That is solving the differential equations x′=vx' = v, v′=F/mv' = F/m one small step at a time. This lesson compares the three integrators games actually use, explicit Euler, semi-implicit Euler and Verlet, and shows why engines run physics on a fixed timestep.

The equations behind every frame

Newton's second law is a second-order ODE, which we split into two first-order ones (as in numerical solutions):

dxdt=vdvdt=a(x,v)=F/m\begin{aligned} \frac{dx}{dt} &= v \\ \frac{dv}{dt} &= a(x, v) = F / m \end{aligned}

A game advances them by a step Δt\Delta t, typically 1/601/60 s. The three classic update rules differ only in which velocity and acceleration they use:

Integrator Update per step Order Energy on a spring
Explicit Euler x←x+v Δtx \leftarrow x + v\,\Delta t; then v←v+a(xold) Δtv \leftarrow v + a(x_{\text{old}})\,\Delta t 1 grows: the system gains energy
Semi-implicit (symplectic) Euler v←v+a(x) Δtv \leftarrow v + a(x)\,\Delta t; then x←x+vnew Δtx \leftarrow x + v_{\text{new}}\,\Delta t 1 stays bounded, oscillates slightly
Velocity Verlet x←x+v Δt+12a Δt2x \leftarrow x + v\,\Delta t + \frac{1}{2}a\,\Delta t^2; a′=a(xnew)a' = a(x_{\text{new}}); v←v+12(a+a′) Δtv \leftarrow v + \frac{1}{2}(a + a')\,\Delta t 2 stays bounded, more accurate

The only difference between the two Euler variants is the order of two lines of code, yet it decides whether an orbit spirals outward or stays closed. More detail on these in game-physics integrators.

A thrown ball

Under constant gravity the exact answer is the parabola y=v0t−12gt2y = v_0 t - \frac{1}{2}gt^2 from motion. Throw a ball upward at 10 m/s and step for one second at 60 Hz:

python · try it yourself
g, dt, steps = 9.81, 1 / 60, 60
v0 = 10.0
exact = v0 * 1.0 - 0.5 * g * 1.0**2

# explicit Euler
y, v = 0.0, v0
for _ in range(steps):
    y, v = y + v * dt, v - g * dt
print(f"explicit Euler  y(1) = {y:.5f}   error {y - exact:+.5f}")

# semi-implicit Euler
y, v = 0.0, v0
for _ in range(steps):
    v -= g * dt
    y += v * dt
print(f"semi-implicit   y(1) = {y:.5f}   error {y - exact:+.5f}")

# velocity Verlet
y, v = 0.0, v0
for _ in range(steps):
    y += v * dt + 0.5 * (-g) * dt**2
    v += (-g) * dt              # a is constant, so ½(a + a') = a
print(f"velocity Verlet y(1) = {y:.5f}   error {y - exact:+.5f}")
print(f"exact           y(1) = {exact:.5f}")
explicit Euler  y(1) = 5.17675   error +0.08175
semi-implicit   y(1) = 5.01325   error -0.08175
velocity Verlet y(1) = 5.09500   error -0.00000
exact           y(1) = 5.09500

Both Euler variants are off by 12g Δt t≈0.08\frac{1}{2} g\,\Delta t\,t \approx 0.08 m, in opposite directions: explicit Euler uses the velocity from the start of each step (too fast going up), semi-implicit the one from the end. Verlet is exact for constant acceleration, because its position update is the Taylor polynomial to second order and the third derivative is zero.

A spring and the energy test

The harder test is oscillation. For a mass on a spring, a=−ω2xa = -\omega^2 x, the energy E=12v2+12ω2x2E = \frac{1}{2}v^2 + \frac{1}{2}\omega^2 x^2 should stay constant forever. Run each method for 20 seconds at a coarse 30 Hz:

python · try it yourself
w2, dt, T = 40.0, 1 / 30, 20.0          # ω² = 40, so ω ≈ 6.3 rad/s
n = int(round(T / dt))
energy = lambda x, v: 0.5 * v * v + 0.5 * w2 * x * x

def run(method):
    x, v = 1.0, 0.0
    lo = hi = energy(x, v)
    for _ in range(n):
        if method == "explicit":
            x, v = x + v * dt, v - w2 * x * dt
        elif method == "semi":
            v -= w2 * x * dt
            x += v * dt
        else:                            # velocity Verlet
            a = -w2 * x
            x += v * dt + 0.5 * a * dt * dt
            v += 0.5 * (a - w2 * x) * dt
        e = energy(x, v)
        lo, hi = min(lo, e), max(hi, e)
    return x, lo, hi

print(f"start energy 20.000")
for m in ["explicit", "semi", "verlet"]:
    x, lo, hi = run(m)
    print(f"{m:8s}: energy range {lo:10.3f} .. {hi:10.3f}   x(20) = {x:9.3f}")
start energy 20.000
explicit: energy range     20.000 .. 4287819469139.025   x(20) = 250911.158
semi    : energy range     18.093 ..     22.357   x(20) =     0.394
verlet  : energy range     19.778 ..     20.000   x(20) =     0.486

Explicit Euler multiplies the energy by 1+ω2Δt21 + \omega^2 \Delta t^2 every step, so after 600 steps the spring is flying apart. The semi-implicit and Verlet versions wobble around the true energy but never drift: they are symplectic, which means they preserve the geometry of the motion even though each step is approximate. That is why almost every game engine uses semi-implicit Euler (Box2D and Bullet, for example) or a Verlet variant (cloth and rope, position-based dynamics).

Fixed timestep

If physics simply uses each frame's duration as Δt\Delta t, the results depend on the frame rate: a fast PC and a slow laptop disagree, replays drift, and networked players desync. The standard fix is an accumulator: add the real frame time to a bank and run physics in fixed steps while enough time is banked. Leftover time is used only to interpolate what is drawn (fixed timestep, determinism).

python · try it yourself
import random

def step(state, dt):                     # semi-implicit Euler, damped spring
    x, v = state
    v += (-40.0 * x - 1.0 * v) * dt
    return (x + v * dt, v)

def play(frames, fixed):
    state, acc, DT, steps = (1.0, 0.0), 0.0, 1 / 64, 0
    for frame_dt in frames:
        if not fixed:
            state = step(state, frame_dt); steps += 1
            continue
        acc += frame_dt
        while acc >= DT:
            state = step(state, DT); acc -= DT; steps += 1
    return state[0], steps

steady = [1 / 64] * 128                  # 2 seconds at 64 fps
rng = random.Random(3)
bumpy = []
while sum(bumpy) < 2.0:                  # frame times of k/256 s, all exact in binary
    bumpy.append(min(rng.randint(2, 12) / 256, 2.0 - sum(bumpy)))

for fixed in [False, True]:
    a, b = play(steady, fixed), play(bumpy, fixed)
    label = "fixed 1/64 s " if fixed else "variable dt  "
    print(f"{label}: steady x = {a[0]:.6f} ({a[1]} steps)   bumpy x = {b[0]:.6f} ({b[1]} steps)")
variable dt  : steady x = 0.364309 (128 steps)   bumpy x = 0.374742 (68 steps)
fixed 1/64 s : steady x = 0.364309 (128 steps)   bumpy x = 0.364309 (128 steps)

With variable Δt\Delta t the same two seconds of game time end in different states. With the accumulator both runs take exactly 128 identical physics steps and agree to every digit, regardless of how the frames were sliced.

In software

  • Engines: Unity's FixedUpdate, Godot's _physics_process and Unreal's physics sub-stepping all implement the fixed-step accumulator; your gameplay code that applies forces belongs there, not in the per-frame update.
  • Spiral of death: if one physics step costs more real time than Δt\Delta t, the bank grows forever. Engines cap the number of steps per frame.
  • Springs everywhere: cameras and UI springs from second-order equations use the same semi-implicit update.
  • Verlet in particle systems: position Verlet xnext=2x−xprev+a Δt2x_{\text{next}} = 2x - x_{\text{prev}} + a\,\Delta t^2 stores no velocity at all, which makes constraints (rope segments, cloth) easy: move the points, and the velocity follows.

Exercises

Exercise 1: One step of each

A ball at height 2 m moves up at 3 m/s, g=10 m/s2g = 10\ \text{m/s}^2, Δt=0.1\Delta t = 0.1 s. Give the new (y,v)(y, v) after one step of explicit Euler and of semi-implicit Euler.

Answer

Explicit: (2.3,2.0)(2.3, 2.0). Semi-implicit: (2.2,2.0)(2.2, 2.0).

Solution
explicit:y=2+3⋅0.1=2.3v=3−10⋅0.1=2.0semi-implicit:v=3−10⋅0.1=2.0y=2+2.0⋅0.1=2.2exact:y=2+0.3−12⋅10⋅0.01=2.25(Verlet gets this)\begin{aligned} &\text{explicit:} && y = 2 + 3 \cdot 0.1 = 2.3 && v = 3 - 10 \cdot 0.1 = 2.0 \\ &\text{semi-implicit:} && v = 3 - 10 \cdot 0.1 = 2.0 && y = 2 + 2.0 \cdot 0.1 = 2.2 \\ &\text{exact:} && y = 2 + 0.3 - \tfrac{1}{2} \cdot 10 \cdot 0.01 = 2.25 && \text{(Verlet gets this)} \end{aligned}

Exercise 2: Energy factor

Show that one explicit Euler step on a=−ω2xa = -\omega^2 x multiplies E=12v2+12ω2x2E = \frac{1}{2}v^2 + \frac{1}{2}\omega^2 x^2 by exactly 1+ω2Δt21 + \omega^2 \Delta t^2. With ω2=40\omega^2 = 40 and Δt=1/30\Delta t = 1/30, how many steps until the energy doubles?

Answer

Factor 1+40/900≈1.04441 + 40/900 \approx 1.0444; the energy doubles after about 16 steps (about half a second).

Solution
x′=x+vΔt,v′=v−ω2xΔtv′2+ω2x′2=v2−2ω2xvΔt+ω4x2Δt2+ω2x2+2ω2xvΔt+ω2v2Δt2=(v2+ω2x2)(1+ω2Δt2)1+40/900=1.04444;n=ln⁡2/ln⁡1.04444≈15.9  ⇒  16 steps\begin{aligned} &x' = x + v\Delta t, \qquad v' = v - \omega^2 x \Delta t \\ v'^2 + \omega^2 x'^2 &= v^2 - 2\omega^2 xv\Delta t + \omega^4 x^2 \Delta t^2 + \omega^2 x^2 + 2\omega^2 xv\Delta t + \omega^2 v^2 \Delta t^2 \\ &= (v^2 + \omega^2 x^2)(1 + \omega^2 \Delta t^2) \\ &1 + 40/900 = 1.04444; \qquad n = \ln 2 / \ln 1.04444 \approx 15.9 \;\Rightarrow\; 16 \text{ steps} \end{aligned}

Exercise 3: How many fixed steps?

A game runs physics at 50 Hz with an accumulator. Frames take 30 ms, 12 ms, 25 ms, 40 ms. How many physics steps run after each frame, and what is left in the accumulator at the end?

Answer

1, 1, 1, 2 steps (5 in total); 7 ms remain.

Solution
text
Δt = 20 ms
frame 1: bank 0 + 30  = 30 → 1 step, left 10
frame 2: bank 10 + 12 = 22 → 1 step, left 2
frame 3: bank 2 + 25  = 27 → 1 step, left 7
frame 4: bank 7 + 40  = 47 → 2 steps, left 7

The same as a loop:

python · try it yourself
acc, DT, total = 0, 20, 0
for frame in [30, 12, 25, 40]:
    acc += frame
    n = 0
    while acc >= DT:
        acc -= DT; n += 1
    total += n
    print(f"frame {frame} ms: {n} step(s), left {acc} ms")
print("total steps:", total)
frame 30 ms: 1 step(s), left 10 ms
frame 12 ms: 1 step(s), left 2 ms
frame 25 ms: 1 step(s), left 7 ms
frame 40 ms: 2 step(s), left 7 ms
total steps: 5

5 steps simulate 100 ms of physics for 107 ms of frames; the 7 ms left over are used to interpolate the drawing.

Test yourself

What distinguishes semi-implicit Euler from explicit Euler?

  1. It uses a smaller time step
  2. It updates velocity first and moves the position with the new velocity
  3. It needs the acceleration at two points
  4. It solves an equation each step

Why do games run physics on a fixed timestep?

  1. To make rendering faster
  2. So results do not depend on the frame rate, which keeps replays and network play in sync
  3. Because variable steps are illegal in C++
  4. To avoid using floats

For constant acceleration (a thrown ball, no drag), which integrator gives the exact position?

  1. Explicit Euler
  2. Semi-implicit Euler
  3. Velocity Verlet
  4. None of them