Collision Timing with Quadratics
When something moves in a straight line, its position is a linear function of time, and "when does it touch that circle?" becomes a quadratic equation in . Solving it gives the exact moment of impact, even between two frames, which is how games stop fast bullets from passing through walls. This lesson builds that quadratic for a moving point, for two moving circles, and for a ray.
Motion as a linear function of t
A point that starts at and moves with constant velocity is at
It touches a circle with centre and radius when its distance to equals . Squaring removes the square root (see vector length):
Write (where the point starts, relative to the centre) and expand with the dot product ():
That is an ordinary quadratic with , , .
Reading the answer
The discriminant and the signs tell the whole story:
| Case | Meaning |
|---|---|
| not moving: hit only if already inside () | |
| the point starts inside the circle: report | |
| the line misses the circle | |
| the path just grazes it | |
| it enters at and leaves at |
Only is a real future hit; a negative means the circle was behind the starting point. In a game loop, where is measured in frames, a hit "this frame" means .
import math
def time_of_impact(p0, v, c, r):
"""Earliest t >= 0 at which p0 + v*t is at distance r from c, or None."""
dx, dy = p0[0] - c[0], p0[1] - c[1]
A = v[0]**2 + v[1]**2
B = 2 * (dx * v[0] + dy * v[1])
C = dx * dx + dy * dy - r * r
if C <= 0:
return 0.0 # already touching or inside
disc = B * B - 4 * A * C
if A == 0 or disc < 0:
return None # not moving, or missing
t1 = (-B - math.sqrt(disc)) / (2 * A)
return t1 if t1 >= 0 else None # behind us: no future hit
print(time_of_impact((0, 0), (10, 0), (5, 0), 1)) # straight at it
print(time_of_impact((0, 0), (10, 0), (5, 1), 1)) # grazes the top
print(time_of_impact((0, 0), (10, 0), (5, 3), 1)) # misses
print(time_of_impact((0, 0), (-10, 0), (5, 0), 1)) # moving away
print(time_of_impact((5, 0.5), (1, 0), (5, 0), 1)) # starts inside0.4
0.5
None
None
0.0
The first hit is at : the point travels 4 units of the 10 per frame and touches the circle's left edge at .
Two moving circles
Two circles collide when the distance between their centres equals . Subtract the motions: work in the frame of circle 2, where circle 1 moves with the relative velocity and circle 2 is a fixed circle of radius . It is the same quadratic.
This is what fixes tunnelling. A bullet of radius 0.1 moves 30 units per frame toward a coin of radius 0.5. At the start of the frame they are 15 apart, at the end 15 apart on the other side: checking only the frame positions sees no overlap, yet they passed right through each other.
import math
def circles_toi(p1, v1, r1, p2, v2, r2):
dx, dy = p1[0] - p2[0], p1[1] - p2[1]
wx, wy = v1[0] - v2[0], v1[1] - v2[1]
R = r1 + r2
A, B, C = wx*wx + wy*wy, 2 * (dx*wx + dy*wy), dx*dx + dy*dy - R*R
if C <= 0:
return 0.0
disc = B * B - 4 * A * C
if A == 0 or disc < 0:
return None
t = (-B - math.sqrt(disc)) / (2 * A)
return t if t >= 0 else None
bullet, vb, rb = (0.0, 0.0), (30.0, 0.0), 0.1
coin, vc, rc = (15.0, 0.2), (0.0, 0.0), 0.5
end = (bullet[0] + vb[0], bullet[1] + vb[1])
print("overlap at frame start:", math.dist(bullet, coin) <= rb + rc)
print("overlap at frame end :", math.dist(end, coin) <= rb + rc)
t = circles_toi(bullet, vb, rb, coin, vc, rc)
print(f"swept test: hit at t = {t:.4f}, x = {bullet[0] + vb[0] * t:.3f}")overlap at frame start: False
overlap at frame end : False
swept test: hit at t = 0.4811, x = 14.434
Note: This is continuous collision detection (CCD). Physics engines use it for fast, small objects, together with the broad-phase tricks in game physics.
Ray–circle intersection
A ray is the same motion with a unit direction , so is a distance instead of a time, and . That simplifies the formula to
This "half-b" form saves a few multiplications; it is the version found in ray tracers and mouse-picking code (ray–sphere is the 3D twin).
import math
import matplotlib.pyplot as plt
def ray_circle(o, u, c, r):
dx, dy = o[0] - c[0], o[1] - c[1]
h = dx * u[0] + dy * u[1] # d·u (half of B)
k = dx * dx + dy * dy - r * r # C
disc = h * h - k
if disc < 0:
return None
s = math.sqrt(disc)
return (-h - s, -h + s)
o, ang = (0.0, 0.0), math.radians(20)
u = (math.cos(ang), math.sin(ang))
c, r = (6.0, 3.0), 1.5
t1, t2 = ray_circle(o, u, c, r)
print(f"enter at t = {t1:.4f}, leave at t = {t2:.4f}")
hit = (o[0] + u[0] * t1, o[1] + u[1] * t1)
print(f"hit point = ({hit[0]:.3f}, {hit[1]:.3f})")
fig, ax = plt.subplots(figsize=(6, 4))
ax.add_patch(plt.Circle(c, r, fill=False, color="tab:blue"))
ax.plot([0, u[0] * 9], [0, u[1] * 9], color="tab:orange", label="ray")
ax.plot(*hit, "o", color="tab:red", label="first hit")
ax.set_aspect("equal"); ax.set_xlim(-0.5, 9); ax.set_ylim(-1, 5); ax.legend()enter at t = 5.3751, leave at t = 7.9533
hit point = (5.051, 1.838)
Exercises
Exercise 1: Build the quadratic
A point starts at and moves with velocity per second. The circle has centre and radius 2. Write the quadratic in and find when the point touches the circle.
Answer
, so (enter) and (leave). First contact at s.
Solution
At the point is at , on the circle. ✓
Exercise 2: Hit or miss?
A point starts at and moves with velocity . Does it ever touch the circle with centre and radius 1?
Answer
No: the discriminant is . The closest approach, at , is about 1.90 units from the centre, more than the radius 1.
Solution
, so the line misses the circle.
import math
d, v = (-6, 4), (3, -1)
t = -(d[0]*v[0] + d[1]*v[1]) / (v[0]**2 + v[1]**2) # time of closest approach
closest = (d[0] + v[0]*t, d[1] + v[1]*t)
print(round(t, 3), round(math.hypot(*closest), 4))2.2 1.8974
Exercise 3: Head-on circles (code)
Circle 1: centre , radius 1, velocity . Circle 2: centre , radius 2, velocity . When do they first touch? Check with circles_toi from the lesson.
Answer
Solution
The gap between centres closes at units per second, and they touch when the gap is , so after . With the quadratic: , , , , , , .
import math
def circles_toi(p1, v1, r1, p2, v2, r2):
dx, dy = p1[0] - p2[0], p1[1] - p2[1]
wx, wy = v1[0] - v2[0], v1[1] - v2[1]
R = r1 + r2
A, B, C = wx*wx + wy*wy, 2 * (dx*wx + dy*wy), dx*dx + dy*dy - R*R
disc = B * B - 4 * A * C
return (-B - math.sqrt(disc)) / (2 * A)
print(circles_toi((0, 0), (4, 0), 1, (10, 0), (-2, 0), 2))1.1666666666666667
Test yourself
For a point and a circle , what is the coefficient of ?
The quadratic gives and . What happened?
- No collision
- The hit is at
- The point started inside the circle and leaves it at
- The hit is at from outside
Why does checking overlap only at each frame's end miss some collisions?
- Because floats are inexact
- A fast object can move from one side of a thin target to the other within one frame
- Because circles have no area
- Because the quadratic formula is slow