Collision Detection
Almost every game rule starts with "when X touches Y": the ball hits the paddle, the bullet hits the enemy, the player lands on the floor. Collision code has two jobs: detection (do these two shapes overlap?) and response (what happens now: bounce, push apart, take damage). This lesson builds the detection functions every project in the course uses, tests them without a screen, and then lets you play with them.
Shapes games use
Real sprites have complicated outlines, but games test simple hitboxes around them:
| Shape | Stored as | Typical use |
|---|---|---|
| Point | x, y |
Mouse clicks, bullets that are very small |
| AABB (axis-aligned bounding box) | x, y, w, h (top-left corner + size) |
Platformer characters, tiles, bricks, paddles |
| Circle | x, y, r (centre + radius) |
Balls, coins, round enemies, explosions |
"Axis-aligned" means the box never rotates, which is what makes the test so cheap.
The tests
// Point inside a box
const pointInRect = (px, py, r) => px >= r.x && px < r.x + r.w && py >= r.y && py < r.y + r.h;
// Two boxes overlap when they overlap on BOTH axes
const rectsOverlap = (a, b) =>
a.x < b.x + b.w && a.x + a.w > b.x &&
a.y < b.y + b.h && a.y + a.h > b.y;
// Two circles overlap when the centre distance is less than the sum of the radii.
// Comparing squared distances avoids Math.sqrt.
const circlesOverlap = (a, b) => {
const dx = a.x - b.x, dy = a.y - b.y, r = a.r + b.r;
return dx * dx + dy * dy < r * r;
};
// Circle vs box: find the point of the box closest to the circle centre
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
const circleRect = (c, r) => {
const nx = clamp(c.x, r.x, r.x + r.w), ny = clamp(c.y, r.y, r.y + r.h);
const dx = c.x - nx, dy = c.y - ny;
return dx * dx + dy * dy < c.r * c.r;
};
const box = { x: 100, y: 100, w: 50, h: 30 };
console.log('point (120, 110):', pointInRect(120, 110, box));
console.log('point (150, 110):', pointInRect(150, 110, box), '(right edge is outside)');
console.log('boxes overlap:', rectsOverlap(box, { x: 140, y: 120, w: 20, h: 20 }));
console.log('boxes touch only:', rectsOverlap(box, { x: 150, y: 100, w: 20, h: 20 }));
console.log('circles:', circlesOverlap({ x: 0, y: 0, r: 5 }, { x: 6, y: 8, r: 5 }), circlesOverlap({ x: 0, y: 0, r: 5 }, { x: 6, y: 8, r: 6 }));
console.log('circle near corner:', circleRect({ x: 160, y: 140, r: 12 }, box), circleRect({ x: 156, y: 136, r: 12 }, box));point (120, 110): true
point (150, 110): false (right edge is outside)
boxes overlap: true
boxes touch only: false
circles: false true
circle near corner: false true
Two details worth noticing. Boxes that only touch (one's right edge equals the other's left edge) do not overlap; with < instead of <= a character standing exactly on the floor is not "inside" it. And a circle near a box corner is tested against the corner point, not against a bigger box around the circle; that is why (160, 140) misses although it is within 12 pixels of the box on each axis separately.
Response: how far to push back
Detection says yes, they overlap. To separate them you need the overlap depth on each axis. The axis with the smaller overlap is the side they collided on, and pushing along it moves the shape out with the least movement. This is the minimum translation vector (MTV):
function aabbPush(a, b) {
// How far a must move to leave b, or null if they don't overlap
const dx1 = b.x + b.w - a.x; // push right
const dx2 = a.x + a.w - b.x; // push left
const dy1 = b.y + b.h - a.y; // push down
const dy2 = a.y + a.h - b.y; // push up
if (dx1 <= 0 || dx2 <= 0 || dy1 <= 0 || dy2 <= 0) return null;
const px = dx1 < dx2 ? dx1 : -dx2;
const py = dy1 < dy2 ? dy1 : -dy2;
return Math.abs(px) < Math.abs(py) ? { x: px, y: 0, side: px > 0 ? 'left side of a' : 'right side of a' }
: { x: 0, y: py, side: py > 0 ? 'top of a' : 'bottom of a' };
}
const wall = { x: 100, y: 0, w: 20, h: 200 };
const floor = { x: 0, y: 180, w: 300, h: 20 };
console.log(aabbPush({ x: 85, y: 50, w: 20, h: 20 }, wall)); // walked into the wall from the left
console.log(aabbPush({ x: 40, y: 165, w: 20, h: 20 }, floor)); // fell 5 px into the floor
console.log(aabbPush({ x: 0, y: 0, w: 20, h: 20 }, wall)); // nowhere near{ x: -5, y: 0, side: 'right side of a' }
{ x: 0, y: -5, side: 'bottom of a' }
null
Each project uses a version of this: Breakout picks the bounce direction from it, and the platformer resolves the player against tiles one axis at a time.
Tunneling
Collision tests look at where things are now. A ball moving 600 px/s moves 10 pixels per update at 60 updates per second; if a wall is only 6 pixels thick, the ball can be in front of it in one update and behind it in the next, without ever overlapping it. This is called tunneling. Fixes, from simplest:
- Keep walls thicker than the fastest object's movement per update, or cap speeds.
- Use a fixed step (smaller, steady steps; see the fixed-step loop).
- Split a fast movement into several sub-steps and test each.
- For bullets, test the line segment from the old to the new position (a raycast) instead of the shape.
Many objects: broad phase
Testing every pair of 500 objects is 124,750 tests per update. Games first run a cheap broad phase that finds the pairs that might collide, for example by putting objects into the cells of a coarse grid and only testing objects that share a cell. The exact tests above are then the narrow phase. For the games in this course (tens of objects), testing all pairs is fine.
Play with it
Move the white box with arrows/WASD and the circle with the mouse (or a finger). Shapes turn red when they overlap. Hold Space to switch on the push-out response for the white box, which then slides along the gray blocks instead of entering them.
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set(); // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
ctx.save();
ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
ctx.restore();
}
function run(update, draw, help = '') {
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (active) {
acc += dt;
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
draw();
} else if (!idleDrawn) {
draw(); banner('Click to play', help); idleDrawn = true;
}
requestAnimationFrame(frame);
});
}
// ---- end of play kit ----
const rectsOverlap = (a, b) => a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
const circleRect = (c, r) => {
const dx = c.x - clamp(c.x, r.x, r.x + r.w), dy = c.y - clamp(c.y, r.y, r.y + r.h);
return dx * dx + dy * dy < c.r * c.r;
};
function aabbPush(a, b) {
const dx1 = b.x + b.w - a.x, dx2 = a.x + a.w - b.x, dy1 = b.y + b.h - a.y, dy2 = a.y + a.h - b.y;
if (dx1 <= 0 || dx2 <= 0 || dy1 <= 0 || dy2 <= 0) return null;
const px = dx1 < dx2 ? dx1 : -dx2, py = dy1 < dy2 ? dy1 : -dy2;
return Math.abs(px) < Math.abs(py) ? { x: px, y: 0 } : { x: 0, y: py };
}
const player = { x: 40, y: 40, w: 28, h: 28 };
const ball = { x: 380, y: 200, r: 18 };
const blocks = [
{ x: 140, y: 60, w: 60, h: 150 },
{ x: 260, y: 30, w: 150, h: 40 },
{ x: 290, y: 150, w: 40, h: 40 },
];
cv.addEventListener('pointermove', (e) => {
const r = cv.getBoundingClientRect();
ball.x = (e.clientX - r.left) * (W / r.width);
ball.y = (e.clientY - r.top) * (H / r.height);
});
function update(dt) {
const sp = 150 * dt;
if (keys.has('ArrowLeft') || keys.has('KeyA')) player.x -= sp;
if (keys.has('ArrowRight') || keys.has('KeyD')) player.x += sp;
if (keys.has('ArrowUp') || keys.has('KeyW')) player.y -= sp;
if (keys.has('ArrowDown') || keys.has('KeyS')) player.y += sp;
player.x = clamp(player.x, 0, W - player.w);
player.y = clamp(player.y, 0, H - player.h);
if (keys.has('Space')) {
for (const b of blocks) {
const push = aabbPush(player, b);
if (push) { player.x += push.x; player.y += push.y; }
}
}
}
function draw() {
ctx.fillStyle = '#12161f'; ctx.fillRect(0, 0, W, H);
for (const b of blocks) {
const hit = rectsOverlap(player, b) || circleRect(ball, b);
ctx.fillStyle = hit ? '#e53935' : '#546e7a';
ctx.fillRect(b.x, b.y, b.w, b.h);
}
const boxHitsBall = circleRect(ball, player);
ctx.fillStyle = boxHitsBall ? '#ffeb3b' : '#fff';
ctx.fillRect(Math.round(player.x), Math.round(player.y), player.w, player.h);
ctx.strokeStyle = boxHitsBall ? '#ffeb3b' : '#4fc3f7'; ctx.lineWidth = 3;
ctx.beginPath(); ctx.arc(Math.round(ball.x), Math.round(ball.y), ball.r, 0, Math.PI * 2); ctx.stroke();
ctx.fillStyle = '#fff'; ctx.font = '13px system-ui, sans-serif'; ctx.textAlign = 'left';
ctx.fillText(keys.has('Space') ? 'Push-out: ON' : 'Push-out: off (hold Space)', 10, 262);
}
run(update, draw, 'Arrows/WASD move the box, the mouse moves the circle');
</script>Test yourself
Box A is {x: 0, y: 0, w: 10, h: 10} and box B is {x: 10, y: 5, w: 10, h: 10}. Do they overlap with the strict < test?
- Yes, they share the edge x = 10
- No, they only touch; the overlap on the x axis is zero
- Yes, because they overlap on the y axis
- It depends on the frame rate
A box overlaps a wall by 3 px on the x axis and 12 px on the y axis. Which way should it be pushed?
- Along y, by 12 px
- Along x, by 3 px
- Diagonally
- Not at all
A very fast bullet passes through a thin wall without a hit. What is this called, and what is a good fix for bullets?
- Ghosting; use bigger sprites
- Tunneling; test the segment from the old to the new position (a raycast)
- Aliasing; turn on image smoothing
- Clipping; use circles instead of boxes