Tunneling and Continuous Collision Detection
A physics engine doesn't simulate motion; it simulates snapshots of motion, one per step. Everything in between is never looked at. If an object moves farther in one step than the thickness of what it should hit, the snapshot before is on one side, the snapshot after is on the other side, and no step ever sees an overlap. The object tunnels through. Bullets fly through walls, a fast ball escapes the arena, a falling player drops through a thin floor after a long fall.
Why it happens, in numbers
A ball of radius 0.1 m flies at a wall 0.2 m thick, with 60 physics steps per second:
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::fixed << std::setprecision(3);
const double r = 0.1, wallMin = 10.0, wallMax = 10.2, dt = 1.0 / 60;
for (double speed : {20.0, 60.0}) {
std::cout << "speed " << speed << " m/s, moves " << speed * dt << " m per step\n";
double x = 8.85;
bool hit = false;
for (int step = 1; step <= 6 && !hit; step++) {
x += speed * dt;
bool overlap = x + r > wallMin && x - r < wallMax; // discrete test at this snapshot only
std::cout << " step " << step << ": x = " << x << (overlap ? " <- overlap detected" : "") << "\n";
hit = overlap;
}
if (!hit) std::cout << " ...the ball is past the wall and no step ever saw it\n";
}
std::cout << "largest safe step distance: wall + diameter = " << (wallMax - wallMin) + 2 * r << " m\n";
}speed 20.000 m/s, moves 0.333 m per step
step 1: x = 9.183
step 2: x = 9.517
step 3: x = 9.850
step 4: x = 10.183 <- overlap detected
speed 60.000 m/s, moves 1.000 m per step
step 1: x = 9.850
step 2: x = 10.850
step 3: x = 11.850
step 4: x = 12.850
step 5: x = 13.850
step 6: x = 14.850
...the ball is past the wall and no step ever saw it
largest safe step distance: wall + diameter = 0.400 m
At 20 m/s the ball moves 0.333 m per step and one snapshot lands inside the wall. At 60 m/s it moves 1 m per step, jumps from in front of the wall to behind it, and the discrete test never fires. The rule of thumb: tunneling becomes possible as soon as speed * dt exceeds the wall thickness plus the object's diameter. That is only 24 m/s here, much slower than any bullet (hundreds of m/s) and not much faster than a falling player after a long drop.
Ways out, from cheapest to most general:
| Fix | Cost | Limits |
|---|---|---|
| Thicker walls and floors | free | only for level geometry you control |
| Smaller steps / sub-stepping | CPU for everything | just moves the speed limit |
| Clamp the maximum speed | free | changes gameplay |
| Raycast fast, small things (bullets) | one ray per step | treats the projectile as a point or thin shape; see queries |
| Swept tests (CCD) | extra tests for fast bodies | needs time-of-impact code per shape pair |
| Speculative contacts | cheap | can produce "ghost" collisions near corners |
Sweeping: time of impact
Continuous collision detection looks at the whole path of the step, not just its end. For a sphere moving in a straight line against a plane, the signed distance from the plane changes linearly from d0 at the start of the step to d1 at the end. The sphere first touches when that distance equals the radius:
t = (d0 - r) / (d0 - d1) hit during this step if 0 <= t <= 1For two moving spheres, work in A's frame: B moves with the relative velocity v = vB - vA from relative position p = pB - pA, and they touch when |p + v·t| = rA + rB. Squaring gives a quadratic in t; the smaller root is the time of impact (TOI). This is the same algebra as ray–sphere, with the ray as the relative motion and the sphere radius rA + rB.
#include <iostream>
#include <iomanip>
#include <cmath>
struct Vec2 { double x, y; };
Vec2 operator+(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
Vec2 operator*(Vec2 v, double s) { return {v.x * s, v.y * s}; }
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
// Sphere moving from p0 to p1 against the plane dot(n, x) = d (n unit length). Returns t in [0,1] or -1.
double sweepSpherePlane(Vec2 p0, Vec2 p1, double r, Vec2 n, double d) {
double d0 = dot(n, p0) - d, d1 = dot(n, p1) - d;
if (d0 < r) return 0; // already touching at the start
if (d1 >= r) return -1; // still clear at the end
return (d0 - r) / (d0 - d1);
}
// Two spheres moving with constant velocities over one step of length 1. Returns t in [0,1] or -1.
double sweepSphereSphere(Vec2 pa, Vec2 va, double ra, Vec2 pb, Vec2 vb, double rb) {
Vec2 p = pb - pa, v = vb - va;
double R = ra + rb;
double a = dot(v, v), b = 2 * dot(p, v), c = dot(p, p) - R * R;
if (c <= 0) return 0; // overlapping at the start
double disc = b * b - 4 * a * c;
if (a == 0 || disc < 0) return -1; // no relative motion, or they miss
double t = (-b - std::sqrt(disc)) / (2 * a);
return (t >= 0 && t <= 1) ? t : -1;
}
int main() {
std::cout << std::fixed << std::setprecision(3);
// The fast ball from above: one step moves it from x = 9.85 to x = 10.85, wall front face at x = 10.
Vec2 p0{9.85, 0}, p1{10.85, 0};
double t = sweepSpherePlane(p0, p1, 0.1, {-1, 0}, -10.0); // plane x = 10, normal facing the ball
Vec2 hit = p0 + (p1 - p0) * t;
std::cout << "ball vs wall: t = " << t << ", centre at impact x = " << hit.x << "\n";
// Two pucks on a table, velocities in units per step.
double toi = sweepSphereSphere({0, 0}, {4, 0}, 0.5, {6, 0.6}, {-4, 0}, 0.5);
std::cout << "puck vs puck: t = " << toi << ", A at x = " << 0 + 4 * toi << ", B at x = " << 6 - 4 * toi << "\n";
double miss = sweepSphereSphere({0, 0}, {4, 0}, 0.5, {6, 1.2}, {-4, 0}, 0.5);
std::cout << "offset 1.2 instead of 0.6: t = " << miss << " (they pass each other)\n";
}ball vs wall: t = 0.050, centre at impact x = 9.900
puck vs puck: t = 0.650, A at x = 2.600, B at x = 3.400
offset 1.2 instead of 0.6: t = -1.000 (they pass each other)
The wall sweep catches the ball from the 60 m/s run the moment its front touches the face (centre at x = 9.9), only 5% of the way into the step that the discrete test skipped over. In the puck case, the two pucks never overlap at the start (x = 0 and 6) or at the end of the step (x = 4 and 2, already past each other), yet they collide at t = 0.650, when their centres are exactly 1.0 apart. With a vertical offset of 1.2, bigger than the sum of the radii, the quadratic has no real root.
What the engine does with the TOI varies. A simple approach moves the body to the TOI position, resolves the contact, and spends the rest of the step (or simply drops it). A more careful one runs a TOI sub-step for the affected bodies. Doing this for every pair of fast bodies in the right order is expensive, which is why engines make CCD opt-in.
Speculative contacts
Speculative CCD skips the sweep. If two shapes are not touching yet but are closer than the distance they could cover this step (relative speed * dt plus a margin), the engine creates the contact anyway, with a positive separation. The solver then only removes the part of the approaching velocity that would close more than that gap, so the body arrives exactly at the surface instead of passing through:
#include <iostream>
#include <iomanip>
#include <algorithm>
int main() {
std::cout << std::fixed << std::setprecision(3);
const double dt = 1.0 / 60, r = 0.1, wall = 10.0;
double x = 8.85, v = 60.0; // the ball that tunnelled
for (int step = 1; step <= 4; step++) {
double gap = (wall - r) - x; // distance to the wall face (could be 0)
if (gap < v * dt) { // could reach the wall this step: speculative contact
double maxV = gap / dt; // fastest approach that just closes the gap
v = std::min(v, maxV);
}
x += v * dt;
std::cout << "step " << step << ": x = " << x << ", v = " << v << "\n";
}
}step 1: x = 9.850, v = 60.000
step 2: x = 9.900, v = 3.000
step 3: x = 9.900, v = 0.000
step 4: x = 9.900, v = 0.000
In step 1 the ball is still 1.05 m from the wall face, more than the 1 m it can travel, so it keeps its full speed. In step 2 the gap is only 0.05 m, so the contact clamps the velocity to 3 m/s (0.05 m in 1/60 s) and the ball stops exactly at the face. A real solver would then apply restitution in the next step to bounce it. Speculative contacts are cheap and fit naturally into the normal contact solver, which is why Box2D v3, Jolt and Unity's ContinuousSpeculative mode use them. Their weakness is ghost collisions: a contact predicted against a surface the body would have missed (passing close by a corner, for example) can slow it down for no visible reason.
Try it
Press CCD to switch between discrete and swept collision, and Speed to change how fast the ball flies at the thin wall. The faint circles are the positions the physics step actually saw. Without CCD, at high speed, no circle overlaps the wall and the ball passes through; with CCD the sweep finds the impact inside the step and the ball bounces.
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; font-family: system-ui, sans-serif; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; }
.bar { position: absolute; top: 6px; right: 8px; display: flex; gap: 6px; }
button { background: #263238; color: #fff; border: 1px solid #546e7a; border-radius: 4px; padding: 3px 10px; font: 13px system-ui, sans-serif; cursor: pointer; }
</style>
<canvas width="480" height="270"></canvas>
<div class="bar"><button id="ccd">CCD: off</button><button id="spd">Speed: 900 px/s</button></div>
<script>
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const STEP = 1 / 30; // a coarse physics step makes the effect easy to see
const R = 6, WALL_X = 300, WALL_W = 6;
const speeds = [180, 450, 900, 1800];
let speedIndex = 2, ccd = false;
let ball, trail, hits, passes;
function reset() {
ball = { x: 40, y: H / 2 + 20, vx: speeds[speedIndex] };
trail = [];
}
hits = 0; passes = 0; reset();
document.getElementById('ccd').onclick = (e) => { ccd = !ccd; e.target.textContent = `CCD: ${ccd ? 'on' : 'off'}`; reset(); };
document.getElementById('spd').onclick = (e) => {
speedIndex = (speedIndex + 1) % speeds.length;
e.target.textContent = `Speed: ${speeds[speedIndex]} px/s`;
reset();
};
function update(dt) {
const x0 = ball.x, x1 = ball.x + ball.vx * dt;
if (ccd && ball.vx > 0) {
// swept test against the wall's front face: the centre touches at WALL_X - R
const face = WALL_X - R;
if (x0 <= face && x1 >= face) {
const t = (face - x0) / (x1 - x0);
ball.x = face;
ball.vx = -ball.vx * 0.8; // bounce, losing a little energy
trail.push({ x: ball.x, hit: true, t });
hits++;
return;
}
}
ball.x = x1;
// discrete test: only looks at the end of the step
const overlap = ball.x + R > WALL_X && ball.x - R < WALL_X + WALL_W;
if (overlap && ball.vx > 0) {
ball.x = WALL_X - R; ball.vx = -ball.vx * 0.8;
trail.push({ x: ball.x, hit: true });
hits++;
return;
}
trail.push({ x: ball.x, hit: false });
if (ball.x > W + 20) { passes++; reset(); }
if (ball.x < -20) reset();
}
function draw() {
ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#90a4ae'; ctx.fillRect(WALL_X, 40, WALL_W, H - 60);
for (const p of trail.slice(-40)) {
ctx.strokeStyle = p.hit ? '#ef5350' : 'rgba(255,202,40,0.35)';
ctx.beginPath(); ctx.arc(p.x, ball.y, R, 0, Math.PI * 2); ctx.stroke();
}
ctx.fillStyle = '#ffca28';
ctx.beginPath(); ctx.arc(ball.x, ball.y, R, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#fff'; ctx.font = '13px system-ui, sans-serif';
ctx.fillText(`step moves ${(speeds[speedIndex] * STEP).toFixed(0)} px, wall + ball = ${WALL_W + 2 * R} px`, 10, 22);
ctx.fillText(`bounces: ${hits} tunnelled through: ${passes}`, 10, 40);
}
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
acc += Math.min((now - last) / 1000, 0.25);
last = now;
while (acc >= STEP) { update(STEP); acc -= STEP; }
draw();
requestAnimationFrame(frame);
});
</script>At 180 px/s every step moves 6 px, less than the 18 px of wall plus ball, so the discrete test always catches it. From 900 px/s up, the discrete ball usually tunnels; with CCD it never does.
CCD in engines
All major engines leave CCD off by default and let you enable it per body, because it costs time and most bodies don't need it.
| Engine | Setting |
|---|---|
| Unity (PhysX) | Rigidbody.collisionDetectionMode: Discrete (default), Continuous, ContinuousDynamic, ContinuousSpeculative |
| Unreal (Chaos) | Use CCD in a primitive component's physics settings |
| Godot | RigidBody3D.continuous_cd (on/off); RigidBody2D.continuous_cd with cast-ray or cast-shape modes |
| Box2D v3 | dynamic vs static is continuous by default; mark fast dynamic bodies as bullets (isBullet in the body definition) to sweep them against other dynamic bodies |
| Rapier | RigidBodyDesc.setCcdEnabled(true); also "soft CCD", a speculative variant (setSoftCcdPrediction(distance)) |
// Unity 6: a fast physics ball (not a bullet; bullets should be raycasts)
var rb = GetComponent<Rigidbody>();
rb.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
rb.linearVelocity = transform.forward * 40f;Tip: Turn CCD on for the few things that need it (the ball in a ball game, the player in a fast racing game, thrown objects) and leave it off for debris. For actual bullets, skip rigid bodies entirely and use a raycast per step.
Test yourself
A ball of radius 0.25 m flies at a 0.1 m thick wall. At 50 physics steps per second, above which speed can it tunnel?
- 5 m/s
- 17.5 m/s
- 30 m/s
- Never
A sphere of radius 1 is 5 units in front of a plane at the start of a step and 3 units behind it (d1 = -3) at the end. What is the time of impact t?
- 0.375
- 0.5
- 0.625
- No impact
What is the typical weakness of speculative contacts?
- They are slower than sweeps
- Ghost collisions: a predicted contact with a surface the body would have missed
- They don't work with spheres
- They require double precision