Game loop, input and physics · 6 MIN READ

Fix the timestep: an accumulator turns uneven frames into identical simulation steps

Advance a simulation in fixed steps from variable frame times, draw it with an interpolation factor and cap catch-up work after a stall.

A game loop runs on two clocks. The display hands you frames of uneven length; the simulation should advance in identical steps. Decoupling the two with an accumulator makes physics independent of the frame rate, makes every run reproducible, and turns a long stall into bounded slow motion instead of a frozen game.

gamedev · A MAP OF THE IDEA

  1. Read frame time
  2. Clamp and accumulate
  3. Step while acc >= step
  4. Draw with alpha

Useful when

  • Identical inputs produce identical simulations on any display.
  • Stalls degrade into bounded slow motion instead of a freeze.

Watch out

  • Interpolation adds one step of visual latency.
  • Teleports and angle wrap-around need special cases when blending.

Implementation & operation cost: Two copies of the drawn state, an integer accumulator and a clock interface; the real cost is the discipline of never reading the blended state in game logic.

01

Why frame-sized steps break physics

The obvious loop measures the time since the last frame and integrates with it: position += velocity * dt. That ties the physics to whatever the machine delivers. Integration error depends on step size, so the same jump reaches a different apex at 30, 60 and 144 frames per second. A 250 ms stall (a window drag, a long garbage-collection pause on a weak device, a breakpoint) becomes one giant step in which a fast object passes straight through a wall. And because no two runs see the same frame times, a timing bug cannot be replayed, a recorded input file cannot reproduce a match, and two machines running in lockstep drift apart. A fixed step gives every run the same sequence of identical updates; only how often you draw is left to the hardware.

go
last := time.Now()
for running {
	now := time.Now()
	dt := now.Sub(last).Seconds() // whatever the last frame happened to cost
	last = now
	world.Update(dt) // physics now depends on the frame rate
	world.Draw()
}
Read the code

This fragment is the pattern to replace, not code to run. Every Update receives a different dt, so the same inputs produce different trajectories on different machines, and a single slow frame turns into a single large, unstable integration step.

02

Consume frame time in fixed steps

The worked program replays seven recorded frame durations through a scripted clock. Each frame adds its duration to an accumulator. While the accumulator holds at least one step, the loop saves the current state as the previous one, integrates one 10 ms step and subtracts the step. Whatever remains is shorter than a step and carries over to the next frame. Time stays in time.Duration, an integer count of nanoseconds, so the accumulator cannot drift the way repeated float additions of 0.016 do; floats appear only inside the physics and in the interpolation factor.

go
package main

import (
	"fmt"
	"time"
)

const (
	step     = 10 * time.Millisecond  // fixed simulation step: 100 updates per second
	maxFrame = 100 * time.Millisecond // never simulate more than this per frame
	speed    = 50.0                   // units per second
)

// Clock is the only source of time the loop sees.
type Clock interface {
	Now() time.Duration
}

// scriptedClock replays recorded frame durations instead of reading the OS clock.
type scriptedClock struct {
	now    time.Duration
	frames []time.Duration
}

func (c *scriptedClock) Now() time.Duration { return c.now }

func (c *scriptedClock) Advance() bool {
	if len(c.frames) == 0 {
		return false
	}
	c.now += c.frames[0]
	c.frames = c.frames[1:]
	return true
}

type State struct{ X float64 }

func integrate(s State, dt time.Duration) State {
	s.X += speed * dt.Seconds()
	return s
}

type Loop struct {
	clock      Clock
	last       time.Duration
	acc        time.Duration
	prev, curr State
	steps      int
	dropped    time.Duration
}

type Report struct {
	Raw, Used time.Duration
	Steps     int
	Alpha     float64
	Drawn     State
}

func (l *Loop) Frame() Report {
	now := l.clock.Now()
	r := Report{Raw: now - l.last}
	l.last = now
	r.Used = min(r.Raw, maxFrame)
	l.dropped += r.Raw - r.Used
	l.acc += r.Used
	for l.acc >= step {
		l.prev = l.curr
		l.curr = integrate(l.curr, step)
		l.acc -= step
		r.Steps++
	}
	l.steps += r.Steps
	r.Alpha = float64(l.acc) / float64(step)
	r.Drawn = State{X: l.prev.X + (l.curr.X-l.prev.X)*r.Alpha}
	return r
}

func main() {
	ms := func(v ...int) []time.Duration {
		out := make([]time.Duration, len(v))
		for i, n := range v {
			out[i] = time.Duration(n) * time.Millisecond
		}
		return out
	}
	clock := &scriptedClock{frames: ms(16, 16, 16, 33, 4, 250, 16)}
	loop := &Loop{clock: clock}
	for n := 1; clock.Advance(); n++ {
		r := loop.Frame()
		dt := r.Raw.String()
		if r.Used != r.Raw {
			dt += " clamped to " + r.Used.String()
		}
		fmt.Printf("frame %d: %s, steps=%d alpha=%.2f draw x=%.2f\n", n, dt, r.Steps, r.Alpha, r.Drawn.X)
	}
	fmt.Printf("%d steps simulated %v; %v dropped of %v\n",
		loop.steps, time.Duration(loop.steps)*step, loop.dropped, clock.Now())
}
Read the code

Frame 1 brings 16 ms: one step runs and 6 ms stays in the accumulator, so alpha is 0.60. Frame 2 adds 16 ms to those 6 and runs two steps. Frame 5 lasts only 4 ms, so no step runs at all, yet the drawn position still moves from 3.55 to 3.75 because alpha grew. Frame 6 stalls for 250 ms; the loop clamps it to 100 ms, runs ten steps instead of twenty-five and records 150 ms as dropped. The last line reports 20 steps, 200 ms of simulated time, against 351 ms on the clock.

03

Draw between the last two states

After the step loop, the leftover time is a fraction of a step: alpha = accumulator / step, always at least 0 and below 1. Drawing prev + (curr - prev) * alpha shows where the object is at the moment of the frame, so motion looks smooth even when the frame rate and the step rate do not divide evenly. The price is one step of latency: every drawn x in the output equals 50 units per second times the time fed into the loop, minus one 10 ms step. At a 60 Hz step that is about 17 ms, which most games accept; some competitive games extrapolate forward instead and live with occasional overshoot. Interpolate only what is continuous. Positions and scales are safe; angles need shortest-arc blending so 350 to 10 degrees does not spin the long way round; a teleport, respawn or screen wrap must set prev equal to curr, or the sprite visibly slides across the map for one frame. Interpolation is purely visual: game rules, collisions and input handling always read curr, never the blend.

04

Clamp catch-up work to avoid the spiral of death

If one step costs more real time than it simulates, each frame owes more steps than the one before, each frame takes longer still, and the game locks up trying to catch up: the spiral of death. A milder version follows every stall, when hundreds of owed steps arrive at once. Clamping the frame time bounds the work: with maxFrame at 100 ms and a 10 ms step, no frame ever runs more than ten steps. The game slows down during an overload instead of freezing, and the Report value makes the dropped time visible so you can log it. Capping steps per frame works the same way. Pick the bound from measurements: if the slowest device you support spends a large share of the step length inside one Update, the fix is a cheaper step or a longer one, not a larger clamp. Lockstep multiplayer cannot drop time, because every peer must simulate every tick; there you slow the whole session down or resynchronize.

05

Inject the clock and test the loop

The loop never calls time.Now; it asks a Clock. Production passes an adapter over the monotonic clock, tests pass a script of frame durations, and every timing edge case becomes a deterministic table row: a zero-length frame, a frame of exactly one step, a stall just above the clamp, a long run whose step count must equal the time fed in divided by the step. Assert on step counts and on curr, not only on the drawn value, because alpha can hide a missing or extra step. If you use Ebitengine, the outer loop already exists: the engine calls your Update at a fixed tick rate, sometimes zero and sometimes several times per frame, and Draw once per frame, as the next lesson shows. The accumulator here is the model of that behavior and the tool for headless servers, replays and simulations that run outside an engine.

go
// monotonic adapts the OS clock to the Clock interface.
type monotonic struct{ start time.Time }

func (m monotonic) Now() time.Duration { return time.Since(m.start) }

func main() {
	loop := &Loop{clock: monotonic{start: time.Now()}}
	for !quit() {
		r := loop.Frame()
		render(r.Drawn)
	}
}
Read the code

Run this fragment in your own program; quit and render are placeholders for your window and drawing code. time.Now carries a monotonic clock reading and time.Since subtracts monotonic readings, so a wall-clock adjustment such as an NTP correction or a user changing the system time never yields a negative or enormous frame.

TAKE THIS WITH YOU

Advance the simulation only in fixed steps taken from an accumulator, draw prev blended toward curr by alpha, clamp the time fed into the loop, and inject the clock so every timing edge case becomes a reproducible test.

Check your understanding

In a fixed-timestep loop, what is the interpolation factor alpha used for?

Go to the source

Progress stays in this browser. No account needed.