Collision Geometry
Games, drawing apps and physics engines ask the same few geometric questions thousands of times per frame: do these two circles touch, do these boxes overlap, do these two line segments cross, is this point inside that triangle? Each one has a short, exact answer built from distances and cross products. This lesson derives the four classic tests and writes them in Python.
Circle vs circle
Two circles touch or overlap when the distance between their centres is at most the sum of their radii:
Square both sides to skip the square root, which is slower and not needed for a yes/no answer (distance formula):
When they do overlap, the penetration depth tells a physics engine how far to push them apart; for that one number you do need the square root.
Box vs box (AABB)
An axis-aligned bounding box (AABB) is a rectangle whose sides are parallel to the axes, stored as its minimum and maximum corners. Two AABBs overlap exactly when their ranges overlap on both axes:
a.min_x ≤ b.max_x and b.min_x ≤ a.max_x (x ranges overlap)
a.min_y ≤ b.max_y and b.min_y ≤ a.max_y (y ranges overlap)If either axis has a gap, there is a line between the boxes that separates them. That idea, generalised to rotated shapes, is the separating axis theorem (SAT). AABBs are so cheap that engines wrap every object in one and run this test first (AABB).
import math
def circles_overlap(c1, r1, c2, r2):
dx, dy = c1[0] - c2[0], c1[1] - c2[1]
return dx * dx + dy * dy <= (r1 + r2) ** 2
def depth(c1, r1, c2, r2):
return r1 + r2 - math.dist(c1, c2)
def aabb_overlap(a, b): # box = (min_x, min_y, max_x, max_y)
return a[0] <= b[2] and b[0] <= a[2] and a[1] <= b[3] and b[1] <= a[3]
print(circles_overlap((0, 0), 2, (3, 1), 1.5), round(depth((0, 0), 2, (3, 1), 1.5), 4))
print(circles_overlap((0, 0), 2, (4, 3), 3), depth((0, 0), 2, (4, 3), 3))
print(circles_overlap((0, 0), 1, (5, 0), 2))
player = (1, 1, 3, 4)
for name, box in [("crate", (2, 3, 5, 6)), ("wall", (3, 0, 4, 10)), ("coin", (4, 1, 5, 2))]:
print(f"player vs {name}: {aabb_overlap(player, box)}")True 0.3377
True 0.0
False
player vs crate: True
player vs wall: True
player vs coin: False
The second pair touches exactly (distance ), so the depth is 0. The wall shares the edge with the player; with <= touching counts as overlapping, with < it would not. Pick one rule and use it everywhere.
The orientation test
Most of the remaining tests rest on one formula: the 2D cross product of the vectors from to and from to (vectors in geometry):
| Sign | Meaning |
|---|---|
| turns left (counter-clockwise) | |
| turns right (clockwise) | |
| the three points are collinear |
Its absolute value is twice the area of triangle . With integer coordinates it is computed exactly, with no rounding at all.
Segment vs segment
Segments and cross when and lie on opposite sides of line and and lie on opposite sides of line . Opposite sides means the two orientations have opposite signs. If an orientation is 0, the point is on the other segment's line, and we check whether it lies within the segment's bounding box.
To find where they cross, write and solve with cross products: .
Point in triangle
A point lies inside triangle (counter-clockwise) when it is on the left of all three edges: , and are all . Dividing each by the whole triangle's gives the barycentric coordinates of : weights that add up to 1, with . All three are non-negative exactly when is inside. GPUs use these weights to decide which pixels a triangle covers and to blend colours and texture coordinates across it.
def orient(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def on_box(a, b, p): # p collinear with ab: is it between a and b?
return min(a[0], b[0]) <= p[0] <= max(a[0], b[0]) and min(a[1], b[1]) <= p[1] <= max(a[1], b[1])
def segments_cross(p, q, r, s):
o1, o2, o3, o4 = orient(p, q, r), orient(p, q, s), orient(r, s, p), orient(r, s, q)
if o1 * o2 < 0 and o3 * o4 < 0:
return True
return (o1 == 0 and on_box(p, q, r)) or (o2 == 0 and on_box(p, q, s)) or \
(o3 == 0 and on_box(r, s, p)) or (o4 == 0 and on_box(r, s, q))
def crossing_point(p, q, r, s):
d1, d2 = (q[0] - p[0], q[1] - p[1]), (s[0] - r[0], s[1] - r[1])
t = orient((0, 0), (r[0] - p[0], r[1] - p[1]), d2) / orient((0, 0), d1, d2)
return (p[0] + t * d1[0], p[1] + t * d1[1])
print(segments_cross((0, 0), (4, 4), (0, 4), (4, 0)), crossing_point((0, 0), (4, 4), (0, 4), (4, 0)))
print(segments_cross((0, 0), (2, 2), (3, 0), (5, 3)))
print(segments_cross((0, 0), (4, 0), (2, 0), (6, 0)), segments_cross((0, 0), (1, 0), (2, 0), (3, 0)))
def barycentric(a, b, c, p):
area = orient(a, b, c)
return orient(b, c, p) / area, orient(c, a, p) / area, orient(a, b, p) / area
A, B, C = (0, 0), (6, 0), (2, 5)
for P in [(2, 2), (5, 3), (3, 0), A]:
u, v, w = barycentric(A, B, C, P)
print(P, f"u={u:.3f} v={v:.3f} w={w:.3f}", "inside" if min(u, v, w) >= 0 else "outside")True (2.0, 2.0)
False
True False
(2, 2) u=0.400 v=0.200 w=0.400 inside
(5, 3) u=-0.233 v=0.633 w=0.600 outside
(3, 0) u=0.500 v=0.500 w=0.000 inside
(0, 0) u=1.000 v=0.000 w=0.000 inside
The point lies on edge , so : it counts as inside with >= 0. Renderers use a "top-left rule" to decide which of two triangles sharing an edge owns such pixels, so none is drawn twice.
Tip: Keep coordinates as integers (pixels, grid cells) where you can. Orientation tests are then exact. With floats, nearly collinear points can give the wrong sign; robust libraries use exact arithmetic for that case.
In software
- Broad phase, then narrow phase: engines first compare AABBs or circles (cheap), then run exact shape tests only on the pairs that survive (closest point, circles and spheres).
- Rasterisation: every triangle on your screen was filled with the edge test above.
- Maps and CAD: "does this road cross that border?" is segment intersection; the convex hull uses the same orientation test.
Exercises
Exercise 1: Two circles
Circle 1 has centre and radius 3; circle 2 has centre and radius 4. Do they overlap?
Answer
No: the centres are 10 apart and the radii add up to 7.
Solution
Exercise 2: Which side?
Is the point to the left or right of the directed line from to ?
Answer
Right (the orientation is ).
Solution
The orientation is negative, so turns clockwise: is to the right of the line.
def orient(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
print(orient((1, 1), (3, 5), (4, 1)))-12
Exercise 3: Barycentric weights
Find the barycentric coordinates of in the triangle , , . Is inside?
Answer
; inside.
Solution
Check: , and . ✓ All weights are positive, so is inside.
Exercise 4: Box sweep (code)
A player box (0, 0, 2, 2) moves right by 1 unit per step. Write a loop that prints the first step at which it overlaps the box (6.5, 1, 8, 3).
Answer
Step 5 (the player's max reaches ).
Solution
After step the player spans from to . It overlaps when , so , the first whole step is 5. The ranges and overlap all the time.
def aabb_overlap(a, b):
return a[0] <= b[2] and b[0] <= a[2] and a[1] <= b[3] and b[1] <= a[3]
target = (6.5, 1, 8, 3)
for step in range(1, 10):
if aabb_overlap((step, 0, step + 2, 2), target):
print("first overlap at step", step)
breakfirst overlap at step 5
Test yourself
Why compare squared distances in the circle test?
- Squared values are more accurate
- It avoids a square root and gives the same yes/no answer for non-negative values
- Circles are defined by squares
- It handles negative radii
. What do you know?
- , and are collinear
- is inside triangle
- The segments cross
Two AABBs overlap on the -axis but not on the -axis. Do they collide?
- Yes
- Only if they are squares
- No, a horizontal line separates them
- It depends on their areas