The Game Loop and Fixed Timestep
The game loop is the heartbeat of the engine. Every iteration it asks the platform for input, advances the simulation, and draws a frame. The Game Loop and Fixed Timestep lessons of the fundamentals course explain the idea; here we build the engine version: a loop that is driven by a clock interface, runs the simulation in fixed steps, survives hitches, and hands the renderer an interpolation factor.
while running:
now = clock.ticks()
frameDt = now - previous // real elapsed time
pollEvents() // platform layer
accumulator += min(frameDt, maxFrame)
while accumulator >= step: // 0..N fixed updates
simulate(step)
accumulator -= step
alpha = accumulator / step // 0..1, how far into the next step
render(alpha) // draw between previous and current stateWhy a fixed step?
If you simulate with whatever dt the frame happens to take, the result depends on the frame rate. Collisions are missed at low frame rates, springs explode, and a jump reaches a different height at 30 FPS than at 144 FPS. Replays and lockstep multiplayer become impossible, because two machines never produce the same dt sequence.
The program below integrates the same jump with a variable dt at two frame rates, then with a fixed 1/60 s step:
#include <cstdio>
// semi-implicit Euler: update velocity, then position
double jumpPeak(double dt, int frames) {
double y = 0, vy = 5.0, peak = 0;
for (int i = 0; i < frames; i++) {
vy -= 9.81 * dt;
y += vy * dt;
if (y > peak) peak = y;
}
return peak;
}
double jumpPeakFixed(double frameDt, int frames) {
const double step = 1.0 / 60.0;
double y = 0, vy = 5.0, peak = 0, acc = 0;
for (int i = 0; i < frames; i++) {
acc += frameDt;
while (acc >= step - 1e-12) {
vy -= 9.81 * step;
y += vy * step;
if (y > peak) peak = y;
acc -= step;
}
}
return peak;
}
int main() {
std::printf("variable dt, 30 FPS : peak %.4f m\n", jumpPeak(1.0 / 30, 30));
std::printf("variable dt, 144 FPS: peak %.4f m\n", jumpPeak(1.0 / 144, 144));
std::printf("fixed step, 30 FPS : peak %.4f m\n", jumpPeakFixed(1.0 / 30, 30));
std::printf("fixed step, 144 FPS: peak %.4f m\n", jumpPeakFixed(1.0 / 144, 144));
}variable dt, 30 FPS : peak 1.1920 m
variable dt, 144 FPS: peak 1.2569 m
fixed step, 30 FPS : peak 1.2329 m
fixed step, 144 FPS: peak 1.2329 m
With a variable step the peak height depends on the frame rate. With a fixed step both runs execute exactly the same sequence of 1/60 s updates, so they agree to the last digit, no matter how the frames were sliced.
A clock you can replace
Engines read a monotonic high-resolution timer: SDL_GetTicksNS() or SDL_GetPerformanceCounter() in SDL3, glfwGetTime() in GLFW, std::chrono::steady_clock in plain C++. Never use the wall-clock time of day (system_clock), which jumps when the user or NTP changes it.
#include <chrono>
#include <cstdint>
struct SteadyClock {
using clock = std::chrono::steady_clock;
clock::time_point start = clock::now();
std::uint64_t ticksNs() const {
return std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - start).count();
}
};
// With SDL3: Uint64 ns = SDL_GetTicksNS();Hide the clock behind a tiny interface, and the same loop can run on a real timer in the game, on a scripted list of frame times in tests, and on recorded frame times when replaying a bug report. Keep time as integer ticks (nanoseconds or microseconds) for as long as possible: a double of seconds since startup slowly loses precision over a long session, while integer arithmetic stays exact.
The full loop with a simulated clock
This loop uses integer microseconds, a 60 Hz step (16 667 µs, rounded), a clamp against the "spiral of death", and stores the previous and current state so the renderer can interpolate:
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <vector>
// A clock that replays a scripted list of frame durations (microseconds).
struct ScriptedClock {
std::vector<std::int64_t> frames;
std::size_t next = 0;
std::int64_t current = 0;
std::int64_t ticksUs() const { return current; }
bool advance() {
if (next == frames.size()) return false;
current += frames[next++];
return true;
}
};
struct State { double x, v; };
int main() {
const std::int64_t stepUs = 16667; // ~60 Hz simulation
const std::int64_t maxFrameUs = 100000; // never simulate more than 0.1 s per frame
ScriptedClock clock{{16667, 16667, 8000, 25000, 500000, 16667}};
State prev{0, 2}, cur{0, 2}; // moving at 2 m/s
std::int64_t accumulator = 0, last = clock.ticksUs();
int frame = 0, totalSteps = 0;
while (clock.advance()) {
std::int64_t frameUs = clock.ticksUs() - last;
last = clock.ticksUs();
accumulator += std::min(frameUs, maxFrameUs); // clamp hitches
int steps = 0;
while (accumulator >= stepUs) {
prev = cur;
cur.x += cur.v * (stepUs / 1e6);
accumulator -= stepUs;
steps++;
}
totalSteps += steps;
double alpha = double(accumulator) / stepUs;
double drawX = prev.x + (cur.x - prev.x) * alpha; // what the renderer shows
std::printf("frame %d: %6lld us steps=%d alpha=%.2f sim x=%.4f drawn x=%.4f\n",
++frame, (long long)frameUs, steps, alpha, cur.x, drawX);
}
std::printf("total fixed steps: %d\n", totalSteps);
}frame 1: 16667 us steps=1 alpha=0.00 sim x=0.0333 drawn x=0.0000
frame 2: 16667 us steps=1 alpha=0.00 sim x=0.0667 drawn x=0.0333
frame 3: 8000 us steps=0 alpha=0.48 sim x=0.0667 drawn x=0.0493
frame 4: 25000 us steps=1 alpha=0.98 sim x=0.1000 drawn x=0.0993
frame 5: 500000 us steps=6 alpha=0.98 sim x=0.3000 drawn x=0.2993
frame 6: 16667 us steps=1 alpha=0.98 sim x=0.3333 drawn x=0.3327
total fixed steps: 10
Read the output line by line:
- A frame of exactly one step runs one update. An 8 ms frame runs zero updates; the renderer still draws, interpolating part of the way to the next state, so motion stays smooth on a 120 Hz display.
- The 500 ms hitch (a loading stall, a breakpoint) is clamped to 100 ms, so the loop runs 6 steps instead of 30. Without the clamp, a slow frame produces more steps, which makes the next frame slower still: the spiral of death. The game visibly slows down for one frame instead.
drawXlags the simulation by up to one step. That is the price of interpolation: about 16 ms of extra latency, which almost every game accepts. Extrapolating instead (cur.x + cur.v * alpha * step) removes the lag but overshoots on sudden stops.
Note: Which state is interpolated? Only what the renderer needs: transforms (position, rotation as a quaternion slerp) and sometimes the camera. Gameplay never reads the interpolated values; it reads the simulation state.
Variable-rate work around the fixed step
Not everything belongs in the fixed step. A typical frame:
| Runs | Work |
|---|---|
| Once per frame, before the fixed loop | poll events, update input state, read network packets |
| 0..N times, fixed step | gameplay rules, physics, AI decisions, anything that must be deterministic |
| Once per frame, after | animation blending, particles, camera smoothing (with frame-rate-independent damping), audio listener update, UI |
| Once per frame, last | build render commands with alpha, submit, present (vsync waits here) |
Input sampled once per frame but consumed by several fixed steps needs care: a "jump pressed" edge must be consumed by exactly one step, not re-triggered by each. The Input Mapping lesson stores edges until a step consumes them. The physics side (substeps, determinism across machines) is covered in Game Physics & Animation.
Frame pacing and sleeping
With vsync on, SDL_GL_SwapWindow or the swapchain present blocks until the display is ready, which paces the loop. With vsync off, or on a server with no display, the loop must sleep, or it spins a CPU core at 100 %. SDL_DelayNS() and std::this_thread::sleep_for may oversleep by a millisecond or more, depending on the OS timer, so precise limiters sleep for most of the remaining time and spin for the last fraction of a millisecond.
Test yourself
A frame takes 8 ms and the fixed step is 16.67 ms (empty accumulator before). What happens?
- One step runs with dt = 8 ms
- No fixed step runs; the renderer interpolates with alpha ≈ 0.48
- Two steps run
- The frame is skipped and nothing is drawn
What is the 'spiral of death' and how does the loop avoid it?
- Floating-point drift; avoided by using doubles
- A slow frame causes more fixed steps, which make the next frame slower; avoided by clamping the time added per frame
- Infinite recursion in systems; avoided by a stack limit
- Vsync stutter; avoided by disabling vsync
Why keep engine time as integer ticks rather than a double of seconds since startup?
- Integers are always faster
- Integer arithmetic is exact, while a growing double loses precision during long sessions
- Doubles cannot be negative
- GPUs require integer time