Game loop, input and physics · 5 MIN READ

AABB and circle collisions: detect overlap, push out along the shallow axis, sweep fast movers

Test boxes and circles for overlap, compute the minimum push that separates them, and stop fast objects from tunneling with sub-steps or a swept test.

Collision handling has two jobs: detect that two shapes overlap, and decide how to move them apart. Axis-aligned boxes and circles cover most 2D games, and both have exact tests that cost a few comparisons. The failure that bites later is speed: an object that moves farther in one tick than an obstacle is thick can pass through it without ever overlapping it.

gamedev · A MAP OF THE IDEA

  1. Test overlap cheaply
  2. Measure penetration
  3. Push along shallow axis
  4. Sweep or sub-step fast

Useful when

  • Box and circle tests are exact and cost a few comparisons.
  • A swept test finds the time of impact in constant time.

Watch out

  • Minimum-axis pushes snag on tile seams; resolve tiles per axis.
  • Fast movers tunnel unless they are sub-stepped or swept.

Implementation & operation cost: A few dozen lines of geometry; sub-stepping multiplies collision work by the step count for every fast object.

01

Overlap tests that cost a few comparisons

Store a box as a center and half extents. Two boxes overlap when, on both axes, the distance between centers is less than the sum of the half extents; how much less is the penetration depth on that axis. Two circles overlap when the squared distance between centers is less than the squared sum of the radii, so the common miss path never takes a square root. A circle against a box uses the point of the box closest to the circle's center, found by clamping the center into the box; the shapes overlap when that point is closer than the radius. Decide once whether touching counts. These tests use strict comparisons, so shapes that share an edge do not collide, which is exactly the state a resolved collision leaves behind.

02

Resolve along the axis of least penetration

For boxes, the minimum push is along the axis with the smaller penetration, signed away from the other box. It moves the object the shortest distance and usually matches intuition: a box that sinks slightly into a floor is pushed up, not sideways. For circles the push follows the line between the centers. The program resolves one pair of each kind, then fires a bullet that moves 12 units per tick at a wall 2 units thick and compares three ways of checking it: the end position only, sub-steps, and a swept test.

go
package main

import (
	"fmt"
	"math"
)

type Vec struct{ X, Y float64 }

func (a Vec) Add(b Vec) Vec       { return Vec{a.X + b.X, a.Y + b.Y} }
func (a Vec) Sub(b Vec) Vec       { return Vec{a.X - b.X, a.Y - b.Y} }
func (a Vec) Scale(k float64) Vec { return Vec{a.X * k, a.Y * k} }
func (a Vec) Dot(b Vec) float64   { return a.X*b.X + a.Y*b.Y }
func (a Vec) String() string      { return fmt.Sprintf("(%.2f, %.2f)", a.X, a.Y) }

// AABB is an axis-aligned box stored as center and half extents.
type AABB struct{ C, Half Vec }

// Push returns the smallest move that separates a from b, along one axis.
// Touching edges (zero depth) do not count as overlap.
func (a AABB) Push(b AABB) (Vec, bool) {
	d := b.C.Sub(a.C)
	px := a.Half.X + b.Half.X - math.Abs(d.X)
	py := a.Half.Y + b.Half.Y - math.Abs(d.Y)
	if px <= 0 || py <= 0 {
		return Vec{}, false
	}
	if px < py {
		return Vec{-math.Copysign(px, d.X), 0}, true
	}
	return Vec{0, -math.Copysign(py, d.Y)}, true
}

type Circle struct {
	C Vec
	R float64
}

// Push separates circle a from circle b along the line between centers.
func (a Circle) Push(b Circle) (Vec, bool) {
	d := b.C.Sub(a.C)
	rr := a.R + b.R
	d2 := d.Dot(d)
	if d2 >= rr*rr { // compare squared lengths: no square root on the miss path
		return Vec{}, false
	}
	dist := math.Sqrt(d2)
	if dist == 0 {
		return Vec{-rr, 0}, true // same center: pick a fixed direction
	}
	return d.Scale(-(rr - dist) / dist), true
}

// PushFromBox separates a circle from a box via the box's closest point.
func (c Circle) PushFromBox(b AABB) (Vec, bool) {
	lo, hi := b.C.Sub(b.Half), b.C.Add(b.Half)
	q := Vec{max(lo.X, min(c.C.X, hi.X)), max(lo.Y, min(c.C.Y, hi.Y))}
	d := c.C.Sub(q)
	d2 := d.Dot(d)
	if d2 >= c.R*c.R {
		return Vec{}, false
	}
	if d2 == 0 { // center inside the box: fall back to the box rule
		return AABB{c.C, Vec{c.R, c.R}}.Push(b)
	}
	dist := math.Sqrt(d2)
	return d.Scale((c.R - dist) / dist), true
}

// Sweep returns the fraction t in [0, 1] of move at which box a first
// touches b. Growing b by a's half extents turns a into a moving point.
func Sweep(a AABB, move Vec, b AABB) (float64, bool) {
	lo := b.C.Sub(b.Half).Sub(a.Half)
	hi := b.C.Add(b.Half).Add(a.Half)
	tmin, tmax := 0.0, 1.0
	axes := [2][4]float64{
		{a.C.X, move.X, lo.X, hi.X},
		{a.C.Y, move.Y, lo.Y, hi.Y},
	}
	for _, ax := range axes {
		p, d, l, h := ax[0], ax[1], ax[2], ax[3]
		if d == 0 {
			if p <= l || p >= h {
				return 0, false // parallel to this slab and outside it
			}
			continue
		}
		t1, t2 := (l-p)/d, (h-p)/d
		if t1 > t2 {
			t1, t2 = t2, t1
		}
		tmin, tmax = max(tmin, t1), min(tmax, t2)
		if tmin >= tmax {
			return 0, false
		}
	}
	return tmin, true
}

func main() {
	a := AABB{Vec{0, 0}, Vec{2, 2}}
	b := AABB{Vec{3, 1}, Vec{2, 2}}
	push, hit := a.Push(b)
	a.C = a.C.Add(push)
	_, again := a.Push(b)
	fmt.Printf("box vs box: hit=%t push=%v, after push hit=%t\n", hit, push, again)

	c1 := Circle{Vec{0, 0}, 2}
	c2 := Circle{Vec{1.8, 2.4}, 2}
	push, hit = c1.Push(c2)
	fmt.Printf("circle vs circle: hit=%t push=%v\n", hit, push)

	ball := Circle{Vec{5, 1}, 1.5}
	crate := AABB{Vec{2, 0}, Vec{2, 2}}
	push, hit = ball.PushFromBox(crate)
	fmt.Printf("circle vs box: hit=%t push=%v\n", hit, push)

	wall := AABB{Vec{10, 0}, Vec{1, 3}}
	bullet := AABB{Vec{0, 0}, Vec{0.5, 0.5}}
	move := Vec{12, 0} // one tick of travel: wider than the wall
	end := AABB{bullet.C.Add(move), bullet.Half}
	_, hit = end.Push(wall)
	fmt.Printf("bullet discrete: hit=%t, ends at x=%.2f\n", hit, end.C.X)

	// Keep each sub-step at most half the combined thickness along the motion,
	// so an overlap is always seen and the shallow axis points back the way it came.
	maxStep := (2*wall.Half.X + 2*bullet.Half.X) / 2
	n := int(math.Ceil(math.Abs(move.X) / maxStep))
	sub := bullet
	for i := 1; i <= n; i++ {
		sub.C = sub.C.Add(move.Scale(1 / float64(n)))
		if push, hit := sub.Push(wall); hit {
			sub.C = sub.C.Add(push)
			fmt.Printf("bullet %d substeps of %.2f: hit on substep %d, resolved to x=%.2f\n", n, maxStep, i, sub.C.X)
			break
		}
	}

	if t, ok := Sweep(bullet, move, wall); ok {
		fmt.Printf("bullet swept: hit at t=%.3f, contact x=%.2f\n", t, bullet.C.X+move.X*t)
	}
}
Read the code

Box A overlaps B by 1 on x and 3 on y, so it is pushed 1 unit left; afterwards the boxes touch and no longer count as overlapping. The circles are 3 apart with radii summing to 4, so A moves back by 1 along the unit direction (0.6, 0.8). The ball's closest point on the crate is (4, 1), one unit from its center, so it moves 0.5 to the right. The bullet ends at x=12, beyond the wall spanning 9 to 11, and the end-position test misses it. Eight sub-steps of 1.5 units find the overlap at x=9 and push the bullet back to 8.50. Sweep treats the bullet as a point against the wall grown by the bullet's half size and returns the entry fraction t=0.708: the same contact at 8.50 from one test instead of eight.

03

Tunneling and the two standard fixes

Tunneling happens when one tick's motion exceeds the overlap window, the combined thickness of the mover and the obstacle along the direction of motion. Sub-stepping splits the move into pieces no longer than half that combined thickness, so every overlap is seen and the shallow axis still points back toward where the mover came from; its cost grows with speed. A swept test computes the time of impact directly with the slab method: on each axis, find when the moving point enters and leaves the grown box, and a hit is the latest entry before the earliest exit. It is exact and constant-time per obstacle, but with several obstacles you must take the earliest hit and decide what happens to the rest of the motion: stop, slide along the surface or bounce. The cheapest fix is often design: cap speeds, or model bullets as rays.

04

Platformers: move and resolve one axis at a time

Minimum-axis resolution has a known failure on tile maps. A player sliding along a floor made of separate tiles can reach a seam where the horizontal penetration into the next tile is momentarily smaller than the vertical one, and gets pushed sideways: the character snags on a flat floor. The standard fix for grid worlds is to move along x and resolve x against solid tiles using the sign of the motion, then move along y and resolve y. Each axis is pushed back the way it came, so seams never matter, and landing, ceiling bumps and wall stops fall out of which axis collided. Keep minimum-axis and circle resolution for free-moving objects such as pickups, debris and enemies bumping into each other.

go
// moveX moves b horizontally and stops it at the near face of any solid it enters.
func moveX(b *AABB, dx float64, solids []AABB) (blocked bool) {
	b.C.X += dx
	for _, s := range solids {
		if _, hit := b.Push(s); !hit {
			continue
		}
		blocked = true
		if dx > 0 {
			b.C.X = s.C.X - s.Half.X - b.Half.X
		} else if dx < 0 {
			b.C.X = s.C.X + s.Half.X + b.Half.X
		}
	}
	return blocked
}
Read the code

This fragment reuses AABB and Push from the program above and runs in your own project. The overlap test is the same, but the resolution ignores the shallow axis and snaps the box to the near face of the solid, chosen by the sign of dx. A matching moveY does the same vertically and reports a landing when dy is positive in screen coordinates, where y grows downward. Moves longer than a tile still need sub-steps.

05

Test collisions at the boundaries

Collision bugs live at exact boundaries, so test them on purpose: shapes exactly touching (no hit), overlapping by a tiny amount, identical centers (the code must pick a fixed direction rather than divide by zero), a circle whose center is inside the box (the closest point equals the center, so the code falls back to the box rule), zero-length motion in Sweep, and motion parallel to a slab. Every case must give the same answer on every run, which is why these examples print fixed precision; compare floats in tests with a tolerance. Once many bodies interact, resolution order matters too: resolving pairs in a fixed order, such as the sorted pair list of the spatial hash lesson, keeps the outcome deterministic.

TAKE THIS WITH YOU

Use strict overlap tests for boxes and circles, push along the shallow axis or the line between centers, resolve tile movement one axis at a time, and stop tunneling with sub-steps no longer than half the combined thickness or a swept time-of-impact test.

Check your understanding

A bullet passes through a thin wall and no overlap is ever detected. What is the root cause?

Go to the source

Progress stays in this browser. No account needed.