Web Games From Zero · Episode 03
Collision Detection
Collision Detection is Episode 03 of Web Games From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Up to now your sprites have been ghosts. They drift across the screen, they overlap, they pass clean through each other and through every wall — because nothing in the code has ever asked the question "are these two things touching?" Collision detection is that question, and answering it is the single thing that turns a screen-saver of moving rectangles into a world that feels solid. It's the difference between dots floating past each other and Mario standing on a brick.
This episode is a playground where nothing overlaps and nothing tunnels. We'll build the four tests every 2D game leans on — box vs box, circle vs circle, point-in-rect — then the two hard parts nobody warns you about: resolution (once two bodies overlap, which way do you push them apart, and how far?) and swept collision (how do you stop a bullet that moves further in one frame than the wall is thick?). Crank the speed slider, flip the swept toggle off, and watch a fast box punch straight through a wall like it isn't there. Flip it back on and it stops dead. That toggle is the lesson.
What you're looking at
One canvas, one little physics world, six stages of the same idea. The top-right controls pick the stage, scale the speed of moving bodies (so you can force tunneling), toggle swept collision on and off, and toggle attract mode. The badge bottom-left tells you what's interactive; the line bottom-right narrates the stage.
Everything is alive on load: an autopilot drives the blue body in a slow figure-eight
so each test fires over and over with no input from you. The moment you press a key or
drag, the demo hands you the controls (takeOver()) and the hint disappears.
Every stage uses the exact same collision functions — the only thing
that changes is what we draw and which test we call. That's the whole point: a handful
of tiny pure functions, reused everywhere.
Stage 1 — AABB: box vs box
AABB stands for Axis-Aligned Bounding Box: a rectangle whose sides are parallel to the screen axes (no rotation). It's the workhorse of 2D collision because the overlap test is almost insultingly cheap — four comparisons, no square roots, no trig. Two boxes overlap exactly when they overlap on both the x-axis and the y-axis at the same time. If there's a gap on either axis, they're apart. Drive the blue box into the gray one and watch both flash red the instant the rectangles touch.
The trap people fall into is testing only one axis, or getting a sign backwards.
The clean way to think about it: "A is to the left of B, OR A is to the right of B,
OR A is above B, OR A is below B" means they don't touch. Negate
that, simplify, and you get four < comparisons:
Stage 2 — Circle vs circle
Circles are even simpler, and they're what you reach for whenever a box would feel
wrong — coins, bullets, planets, the player's "personal space" bubble. Two circles
touch when the distance between their centers is less than the sum of
their radii. That's it. And there's a classic optimization baked into this stage:
a square root is comparatively expensive, so we compare squared distances
instead and never call Math.sqrt at all for the yes/no test.
In the demo the blue circle chases the gray one; they glow red on contact. Squared- distance is one of those tricks that looks like premature optimization until you're running a few thousand checks a frame — then it's free money.
Stage 3 — Point-in-rect
The simplest test of all, and the one you'll use the most outside physics:
is a single point inside a rectangle? Every button you've ever tapped, every tile you've
clicked, every drag-and-drop target runs this. It's two range checks —
x between the box's left and right, y between its top and
bottom. Move your mouse (or finger) over the demo and the box under the cursor lights
up. In attract mode the "cursor" is driven for you, sweeping across a little grid of
UI-style boxes.
Point-in-rect is also the degenerate case of AABB: a point is just a box with zero width and height, so the same four comparisons collapse into these two pairs.
Stage 4 — Resolution: pushing bodies apart
Detection only answers yes/no. A game needs to do something about a yes — and "teleport the overlap away" looks terrible. The right answer is the Minimum Translation Vector (MTV): the shortest push that separates two overlapping boxes. For AABBs, that's beautiful and simple — compute how far they overlap on x and how far on y, then push out along whichever axis has the smaller overlap. Shoving a body the short way out always looks natural; shoving it the long way makes it teleport across the other box.
In this stage the gray box is a fixed wall and the blue box is constantly nudged into it; watch it get popped out along the nearest face, sliding along the wall instead of sinking in. The thin red arrow is the MTV being applied each frame. The key subtlety you can see here: we resolve one axis, the smaller one — never both at once. Resolving both is what causes the "sticking in corners" bug we'll cover in pitfalls.
Stage 5 — Swept vs discrete (the toggle is the lesson)
Here's the bug that ships in more games than any other. Discrete collision — the kind we've done so far — works like this every frame: move the body to its new position, then check if it overlaps anything. That's fine when bodies move a few pixels per frame. But crank the speed slider up and turn swept off: the blue box now jumps so far in a single step that on one frame it's in front of the wall and on the next it's past it — it was never overlapping on any frame we checked, so it sails right through. That's tunneling, and it's why your fast bullets miss thin enemies.
Flip swept back on and it stops dead against the wall no matter how fast it's going. Swept collision doesn't ask "do I overlap after moving?" — it asks "at what fraction of this move do I first touch the wall?" It computes a time of impact between 0 and 1 along the velocity and clamps the move to stop exactly at contact. The faster the box, the more obviously discrete fails and swept saves it.
Stage 6 — Playground
Everything at once: a dozen bouncing balls and boxes resolving against the four walls and against each other, every frame, using the same MTV resolution from Stage 4 and the same swept clamp from Stage 5. Nothing overlaps, nothing escapes the box, and if you fling a body with the mouse it slams into the others and shoves them around. This is a real (if tiny) physics sandbox built entirely from the four functions below. Grab one and throw it.
How the code works
The entire collision toolkit is four small pure functions — they take numbers, return numbers, touch no global state. That's deliberate: pure collision math is trivial to test, trivial to reuse, and trivial to reason about. Here are the first two, the yes/no overlap tests for boxes and circles.
// (a) AABB overlap: boxes as {x, y, w, h} with x,y = top-left corner.
// They overlap only if they overlap on BOTH axes at once.
function aabb(a, b) {
return a.x < b.x + b.w && // a's left is past b's right?
a.x + a.w > b.x && // a's right is before b's left?
a.y < b.y + b.h && // ... same on the y-axis
a.y + a.h > b.y;
}
// (b) Circle overlap: {x, y, r} = center + radius.
// Compare SQUARED distance vs squared radii — no sqrt needed.
function circles(a, b) {
const dx = b.x - a.x, dy = b.y - a.y;
const rr = a.r + b.r;
return dx * dx + dy * dy < rr * rr; // touching when centers closer than r1+r2
}
Point-in-rect is the one you'll paste into UI code forever. A point is inside a box
when its x sits within the box's horizontal span and its y
within the vertical span — four comparisons, same shape as AABB:
// (b) point-in-rect: is (px, py) inside box {x, y, w, h}?
// This is hit-testing for buttons, tiles, drag targets — and AABB with a zero-size box.
function pointInRect(px, py, b) {
return px >= b.x && px <= b.x + b.w &&
py >= b.y && py <= b.y + b.h;
}
Now the interesting one. Resolution turns "yes, they overlap" into "here's the push to fix it." For two AABBs we measure the penetration depth on each axis, then return the smaller one as a vector — the Minimum Translation Vector. The sign is chosen from the direction between the centers so we always push out, never deeper in:
// (c) MTV resolution: shortest push that separates two overlapping AABBs.
// Returns {x, y} push (apply to box a), or null if they aren't overlapping.
function resolveAABB(a, b) {
// signed overlap on each axis (positive == overlapping)
const ox = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
const oy = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
if (ox <= 0 || oy <= 0) return null; // a gap on either axis = no hit
const acx = a.x + a.w / 2, bcx = b.x + b.w / 2;
const acy = a.y + a.h / 2, bcy = b.y + b.h / 2;
if (ox < oy) { // x-overlap is smaller → push along x
return { x: acx < bcx ? -ox : ox, y: 0 };
} else { // y-overlap is smaller → push along y
return { x: 0, y: acy < bcy ? -oy : oy };
}
}
And finally the cure for tunneling. Swept AABB doesn't move-then-check;
it asks when, along this frame's velocity, the moving box first reaches the wall.
We "inflate" the wall by the mover's size so we can treat the mover as a single point, then
do a slab test on each axis: the time the point enters the box's x-range and y-range,
and the time it exits. First contact is the latest entry; if that happens before the
earliest exit (and within this frame), that fraction t is our time of impact —
clamp the move to it.
// (d) swept AABB: how far (0..1) can box a move by (vx, vy) before it hits box b?
// Returns time-of-impact t in [0,1]; t === 1 means "no hit this frame, full move is safe".
function sweptAABB(a, b, vx, vy) {
// Minkowski: grow b by a's size, shrink a to its top-left point.
const ex = b.x - a.w, ey = b.y - a.h;
const ew = b.w + a.w, eh = b.h + a.h;
let tEnter = 0, tExit = 1;
// --- x axis slab ---
if (vx !== 0) {
const t1 = (ex - a.x) / vx, t2 = (ex + ew - a.x) / vx;
tEnter = Math.max(tEnter, Math.min(t1, t2));
tExit = Math.min(tExit, Math.max(t1, t2));
} else if (a.x <= ex || a.x >= ex + ew) {
return 1; // parallel & already outside the x-band → miss
}
// --- y axis slab ---
if (vy !== 0) {
const t1 = (ey - a.y) / vy, t2 = (ey + eh - a.y) / vy;
tEnter = Math.max(tEnter, Math.min(t1, t2));
tExit = Math.min(tExit, Math.max(t1, t2));
} else if (a.y <= ey || a.y >= ey + eh) {
return 1;
}
if (tEnter > tExit || tEnter < 0 || tEnter > 1) return 1; // no overlap window inside this frame
return tEnter; // first-touch fraction of the move
}
Using it is the easy part. Instead of blindly doing x += vx, you clamp
the move to the time of impact:
// move the box, but never past the first wall it touches this frame
const t = sweptAABB(box, wall, vx, vy);
box.x += vx * t; // t === 1 → full move; t === 0.4 → stop 40% along
box.y += vy * t;
if (t < 1) console.log('hit wall at t=' + t); // stopped exactly at the face
If t came back as 1, nothing was in the way and the body moves fully; if it
came back as 0.4, the body stops 40% of the way along — right at the wall's face. To keep
sliding along the wall after impact you re-run the move on the remaining axis (the
demo does this in the playground), but the clamp above is the whole idea: no move ever
crosses a wall, no matter how fast.
The fixed-timestep loop (still the backbone)
Everything moves inside the same deterministic loop from Episode 01. Collision is just
more work done inside update(STEP) with the constant step — never with a
variable dt, or your tunneling behavior would change with frame rate and the
speed slider would lie to you:
const STEP = 1 / 60; // fixed simulation step (seconds)
let acc = 0, last = performance.now();
function loop(now) {
let dt = (now - last) / 1000; last = now;
if (dt > 0.25) dt = 0.25; // clamp tab-switch gaps (no spiral of death)
acc += dt;
while (acc >= STEP) { update(STEP); acc -= STEP; }
render();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
Common pitfalls
- Tunneling through thin walls. The headline bug, and the reason Stage 5 exists. If a body can move more than half a wall's thickness in one step, discrete detection will eventually miss it. Fixes: use swept collision (time of impact), or sub-step the fast body — split its movement into several smaller moves and check after each. Never trust a single move-then-check for anything that can move fast (bullets, dropped items, anything falling under gravity).
- Resolving both axes at once causes sticking. If you push a body out on x and y in the same frame, it snags on the seams between tiles and shudders in corners. Resolve along the smaller overlap axis only (the MTV), or resolve axis-by-axis (move x, resolve x, then move y, resolve y). Picking one axis is what lets a body slide along a wall instead of catching on it.
- Float jitter at rest. A body sitting exactly on a surface can flip between "overlapping by 0.0001" and "not overlapping" every frame, producing a visible buzz. Use a small epsilon: treat overlaps below it as touching-but-resting, and zero out tiny velocities so bodies actually settle instead of vibrating.
- Resolution order with many bodies. When A, B, and C are all in a pile, pushing A out of B can shove it into C. One pass rarely fully separates a crowd. Cheap fixes: run a few resolution iterations per frame, and always resolve the largest overlap first. The playground does a couple of passes — that's why a tight cluster of balls settles instead of exploding.
- Inconsistent box origin. Decide once whether
x, yis the box's top-left corner or its center, and never mix the two. Half the "my collision is offset by half a tile" bugs are a corner-vs-center mismatch between the test and the draw call. (We use top-left for boxes, center for circles — stay consistent and convert at the boundary.)
Exercises
- Add restitution (bounciness). Right now resolved bodies just stop.
In the playground, after applying the MTV, reflect the velocity component along the push
axis and multiply it by a
restitutionfactor (try0.8): if the push was along x, setvx = -vx * 0.8. Now balls bounce off walls and each other instead of sticking. Push restitution above 1.0 and watch the sandbox gain energy until it's chaos — a great way to feel why stable physics keeps it below 1. - Circle vs AABB. Write
circleVsRect(c, b): find the point on the box closest to the circle's center by clamping the center's x and y to the box's range (cx = clamp(c.x, b.x, b.x+b.w)), then test whether that closest point is withinc.rof the center using squared distance. This is the most useful "mixed shape" test in 2D — it's how a round player collides with square tiles. - Broad-phase grid. The playground currently tests every pair of bodies — that's O(n²) and falls over at a few hundred bodies. Add a simple spatial grid: bucket each body into the cells it overlaps, then only test pairs that share a cell. Far-apart bodies are never compared. This split — cheap "broad phase" to find candidate pairs, exact "narrow phase" to confirm — is how every real engine scales to thousands of objects.
What's next
Episode 04 — Platformer Physics: a jump that feels great. We take this swept-AABB collision and build the most scrutinized 30 milliseconds in game design: the jump. Gravity that's heavier on the way down, variable jump height when you tap vs hold, coyote time so a jump still fires just after you walk off a ledge, and jump buffering so an early press isn't eaten. Collision made the world solid; next we make moving through it feel good.