TExcelTAD
Home › Game Physics & Animation › Debugging Physics

Debugging Physics

A physics bug usually shows up long after its cause. A crate explodes at step 1,180 because a NaN was born at step 900; a replay desyncs after two minutes because one contact was solved in a different order at second 14. Good physics debugging is about making the cause reproducible and then finding the first bad step. This lesson collects the techniques, with runnable versions of the two most useful ones.

1. Make it reproducible: record the inputs

A simulation with a fixed timestep is a pure function: state[n+1] = step(state[n], input[n]). If you record the initial state (or the level and the seed) and the input of every tick, you can replay the session exactly, as often as you like, with a debugger attached. That requires the rules from Determinism:

  • a fixed dt, never the frame time;
  • no wall-clock reads, unordered-container iteration or uninitialized memory inside the step;
  • the same build, compiler flags and (for cross-machine replays) the same floating-point behaviour.

Record cheaply: a per-tick input struct of a few bytes, written to a ring buffer that holds the last minute. When QA hits a bug, the game saves the buffer next to the crash report.

2. Find the first divergent step: state hashing

When a replay or a networked client drifts, you need to know when it drifted. Hash the full physics state after every step (positions, velocities, rotations, as raw bits) and log the hashes. Compare two logs and the first mismatch is the step where to look. FNV-1a is enough for this; it is not a security hash, just a fingerprint.

In the model below, run B has a typical bug: a "wind" value that should be zero is left uninitialized and happens to hold a tiny number when the third body spawns at step 40. The positions still look identical to many decimal places, but the hash catches it at once:

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cstdint>
#include <cstring>
#include <vector>

struct Body { double x, y, vx, vy; };

uint64_t fnv1a(const std::vector<Body>& bodies) {
    uint64_t h = 1469598103934665603ull;                     // FNV offset basis
    for (const Body& b : bodies) {
        unsigned char bytes[sizeof(Body)];
        std::memcpy(bytes, &b, sizeof(Body));                 // hash the exact bits, not printed values
        for (unsigned char c : bytes) { h ^= c; h *= 1099511628211ull; }
    }
    return h;
}

std::vector<uint64_t> runLog(double windOnSpawn) {
    std::vector<Body> bodies{{0, 10, 1, 0}, {3, 12, -1, 0}};
    std::vector<double> wind{0, 0};
    std::vector<uint64_t> log;
    const double dt = 1.0 / 60;
    for (int step = 0; step < 100; step++) {
        if (step == 40) { bodies.push_back({5, 15, 0, 0}); wind.push_back(windOnSpawn); }
        for (size_t i = 0; i < bodies.size(); i++) {
            bodies[i].vx += wind[i] * dt;
            bodies[i].vy += -9.8 * dt;
            bodies[i].x += bodies[i].vx * dt;
            bodies[i].y += bodies[i].vy * dt;
        }
        log.push_back(fnv1a(bodies));
    }
    return log;
}

int main() {
    std::vector<uint64_t> a = runLog(0.0), b = runLog(1e-13);   // B: an uninitialized value
    for (int step : {0, 39, 40, 99})
        std::cout << "step " << std::setw(2) << step << "  A " << std::hex << std::setw(16) << std::setfill('0') << a[step]
                  << "  B " << std::setw(16) << b[step] << std::dec << std::setfill(' ') << "\n";
    for (size_t i = 0; i < a.size(); i++)
        if (a[i] != b[i]) { std::cout << "first divergent step: " << i << "\n"; break; }
}
step  0  A 3a6de956f3858017  B 3a6de956f3858017
step 39  A 5347b8da6225f81a  B 5347b8da6225f81a
step 40  A fdbcf3322fb803e6  B 92e50070d8bd6742
step 99  A fac265690165ed8d  B 53e2461388e113c1
first divergent step: 40

The two runs agree bit for bit up to step 39 and differ from step 40 on, so the search space shrinks from "somewhere in 100 steps" to "whatever happened at step 40": the spawn. In a real engine, log one hash per step per subsystem (bodies, contacts, character controllers), so the first mismatch also tells you which subsystem diverged. Lockstep and rollback netcode send these hashes between peers for the same reason (Multiplayer Game Networking).

3. Catch NaNs at the step where they appear

One NaN spreads to everything it touches: a NaN position makes a NaN AABB, the broad phase pairs it with everything, contacts get NaN normals, and a second later the whole island is gone. The fix is a guard after each step (in debug builds) that checks every body and stops at the first non-finite value, reporting the body and the last good state. A classic source: a body whose collider has zero size in the level file, so its mass is 0 and its inverse mass infinite.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <vector>

struct Body { std::string name; double y, vy, invMass; };

int main() {
    std::cout << std::fixed << std::setprecision(3);
    const double density = 500, dt = 1.0 / 60;
    struct Spec { std::string name; double w, h, y; };
    std::vector<Spec> level{{"crate", 1.0, 1.0, 3.0}, {"plank", 2.0, 0.0, 4.0}};   // plank height typo: 0
    std::vector<Body> bodies;
    for (const Spec& s : level) {
        double mass = density * s.w * s.h;
        bodies.push_back({s.name, s.y, 0, 1.0 / mass});        // 1 / 0 = inf, no error raised
        std::cout << s.name << ": mass " << mass << ", inverse mass " << bodies.back().invMass << "\n";
    }
    for (int step = 1; step <= 200; step++) {
        for (Body& b : bodies) {
            b.vy += -9.8 * dt;
            if (b.y < 0.5 && b.vy < 0) {                                 // ground contact
                double J = -b.vy / b.invMass;                            // impulse that stops the body
                b.vy += J * b.invMass;
            }
            b.y += b.vy * dt;
        }
        for (const Body& b : bodies)                                     // the guard
            if (!std::isfinite(b.y) || !std::isfinite(b.vy)) {
                std::cout << "step " << step << ": " << b.name << " is not finite (y is "
                          << (std::isnan(b.y) ? "NaN" : "inf") << ", vy is " << (std::isnan(b.vy) ? "NaN" : "inf") << ")\n";
                return 0;
            }
    }
    std::cout << "no problems\n";
}
crate: mass 500.000, inverse mass 0.002
plank: mass 0.000, inverse mass inf
step 52: plank is not finite (y is NaN, vy is NaN)

The plank fell normally while nothing touched it. The first contact computed J * invMass with an infinite inverse mass and a zero-mass impulse, 0 * inf, which is NaN; the guard stops at that exact step and names the body. Without the guard the plank would simply vanish, and in a full engine its NaN AABB would flow into the broad phase and into every contact it touches. Better still, validate at load time: reject zero or negative mass, zero-size shapes and non-unit quaternions where data enters the game.

4. Watch the energy

A closed system (no motors, no damping) should never gain energy. Log kinetic plus potential energy every step, and alarm when it rises by more than a small tolerance. Energy growth points to a too-large dt, an explicit Euler integrator (Euler, Semi-Implicit Euler and Verlet), a too-stiff spring, or positional correction that adds velocity. Energy that slowly falls is usually fine: it is damping, friction or restitution doing their job.

5. Slow down, freeze, step

Add three debug controls to every physics project on the first day:

  • time scale (0.1×): Unity's Time.timeScale, Unreal's slomo 0.1, Godot's Engine.time_scale; the fixed step stays the same size, it just runs less often;
  • pause and single-step: run exactly one fixed step per key press, with debug draw on;
  • freeze on event: break into the debugger when a condition fires (penetration deeper than 10 cm, speed above 100 m/s, a NaN), so you see the frame the problem starts, not the aftermath.

6. Shrink the scene

Once you can reproduce it, remove everything that isn't needed: other bodies, scripts, animation, the network. A three-body repro in an empty scene is fast to step through and easy to compare with a reference library (see Physics and Animation Toolkit).

Test yourself

Why hash raw bits rather than printed positions when comparing two runs?

  1. Hashing is faster to read
  2. Printed values are rounded, so a difference in the last bits stays hidden until it grows
  3. Bits are smaller than text
  4. Printing is non-deterministic

A body's collider has zero size in the level file. What happens in a naive engine?

  1. A compile error
  2. Mass 0, infinite inverse mass, and NaN at the first contact (0 × inf)
  3. The body is skipped automatically
  4. It becomes static

Total energy in an undamped test scene rises 3% per second. What is a likely cause?

  1. Friction
  2. An explicit integrator, a too-large dt, a too-stiff spring, or velocity-adding position correction
  3. Sleeping
  4. Restitution below 1