TExcelTAD
Home › Algebra › Collision Timing with Quadratics

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 tt. 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 p0=(x0,y0)p_0 = (x_0, y_0) and moves with constant velocity v=(vx,vy)v = (v_x, v_y) is at

p(t)=p0+vtthat isx(t)=x0+vxt,y(t)=y0+vytp(t) = p_0 + v t \qquad \text{that is} \qquad x(t) = x_0 + v_x t,\quad y(t) = y_0 + v_y t

It touches a circle with centre cc and radius rr when its distance to cc equals rr. Squaring removes the square root (see vector length):

∣p0+vt−c∣2=r2\lvert p_0 + v t - c \rvert^2 = r^2

Write d=p0−cd = p_0 - c (where the point starts, relative to the centre) and expand with the dot product (d⋅v=dxvx+dyvyd \cdot v = d_x v_x + d_y v_y):

(v⋅v)⏟A t2+2(d⋅v)⏟B t+(d⋅d−r2)⏟C=0\underbrace{(v \cdot v)}_{A}\, t^2 + \underbrace{2(d \cdot v)}_{B}\, t + \underbrace{(d \cdot d - r^2)}_{C} = 0

That is an ordinary quadratic at2+bt+c=0a t^2 + b t + c = 0 with A=v⋅vA = v \cdot v, B=2(d⋅v)B = 2(d \cdot v), C=d⋅d−r2C = d \cdot d - r^2.

Reading the answer

The discriminant Δ=B2−4AC\Delta = B^2 - 4AC and the signs tell the whole story:

Case Meaning
A=0A = 0 not moving: hit only if already inside (C≤0C \le 0)
C<0C < 0 the point starts inside the circle: report t=0t = 0
Δ<0\Delta < 0 the line misses the circle
Δ=0\Delta = 0 the path just grazes it
Δ>0\Delta > 0 it enters at t1=−B−Δ2At_1 = \frac{-B - \sqrt{\Delta}}{2A} and leaves at t2=−B+Δ2At_2 = \frac{-B + \sqrt{\Delta}}{2A}

Only t1≥0t_1 \ge 0 is a real future hit; a negative t1t_1 means the circle was behind the starting point. In a game loop, where tt is measured in frames, a hit "this frame" means 0≤t1≤10 \le t_1 \le 1.

python · try it yourself
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 inside
0.4
0.5
None
None
0.0

The first hit is at t=0.4t = 0.4: the point travels 4 units of the 10 per frame and touches the circle's left edge at x=4x = 4.

Two moving circles

Two circles collide when the distance between their centres equals r1+r2r_1 + r_2. Subtract the motions: work in the frame of circle 2, where circle 1 moves with the relative velocity v1−v2v_1 - v_2 and circle 2 is a fixed circle of radius r1+r2r_1 + r_2. 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.

python · try it yourself
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 uu, so tt is a distance instead of a time, and A=u⋅u=1A = u \cdot u = 1. That simplifies the formula to

t2+2(d⋅u) t+(d⋅d−r2)=0⇒t=−(d⋅u)±(d⋅u)2−(d⋅d−r2)t^2 + 2(d \cdot u)\, t + (d \cdot d - r^2) = 0 \quad\Rightarrow\quad t = -(d \cdot u) \pm \sqrt{(d \cdot u)^2 - (d \cdot d - r^2)}

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).

python · try it yourself
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 (−6,0)(-6, 0) and moves with velocity (2,0)(2, 0) per second. The circle has centre (0,0)(0, 0) and radius 2. Write the quadratic in tt and find when the point touches the circle.

Answer

4t2−24t+32=04t^2 - 24t + 32 = 0, so t=2t = 2 (enter) and t=4t = 4 (leave). First contact at t=2t = 2 s.

Solution
d=(−6,0),v=(2,0)A=v⋅v=4B=2(d⋅v)=2(−12)=−24C=d⋅d−r2=36−4=324t2−24t+32=0⇒t2−6t+8=0⇒(t−2)(t−4)=0\begin{aligned} d &= (-6, 0),\quad v = (2, 0) \\ A &= v \cdot v = 4 \\ B &= 2(d \cdot v) = 2(-12) = -24 \\ C &= d \cdot d - r^2 = 36 - 4 = 32 \\ &4t^2 - 24t + 32 = 0 \quad\Rightarrow\quad t^2 - 6t + 8 = 0 \quad\Rightarrow\quad (t - 2)(t - 4) = 0 \end{aligned}

At t=2t = 2 the point is at (−2,0)(-2, 0), on the circle. ✓

Exercise 2: Hit or miss?

A point starts at (0,4)(0, 4) and moves with velocity (3,−1)(3, -1). Does it ever touch the circle with centre (6,0)(6, 0) and radius 1?

Answer

No: the discriminant is −104<0-104 < 0. The closest approach, at t=2.2t = 2.2, is about 1.90 units from the centre, more than the radius 1.

Solution
d=(0−6,4−0)=(−6,4),v=(3,−1)A=9+1=10B=2(−18−4)=−44C=36+16−1=51Δ=442−4⋅10⋅51=1936−2040=−104\begin{aligned} d &= (0 - 6, 4 - 0) = (-6, 4),\quad v = (3, -1) \\ A &= 9 + 1 = 10 \\ B &= 2(-18 - 4) = -44 \\ C &= 36 + 16 - 1 = 51 \\ \Delta &= 44^2 - 4 \cdot 10 \cdot 51 = 1936 - 2040 = -104 \end{aligned}

Δ<0\Delta < 0, so the line misses the circle.

python · try it yourself
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 (0,0)(0, 0), radius 1, velocity (4,0)(4, 0). Circle 2: centre (10,0)(10, 0), radius 2, velocity (−2,0)(-2, 0). When do they first touch? Check with circles_toi from the lesson.

Answer

t=76≈1.1667t = \frac{7}{6} \approx 1.1667

Solution

The gap between centres closes at 4+2=64 + 2 = 6 units per second, and they touch when the gap is 1+2=31 + 2 = 3, so after (10−3)/6=76(10 - 3)/6 = \frac{7}{6}. With the quadratic: d=(−10,0)d = (-10, 0), w=(6,0)w = (6, 0), A=36A = 36, B=−120B = -120, C=100−9=91C = 100 - 9 = 91, Δ=14400−13104=1296=362\Delta = 14400 - 13104 = 1296 = 36^2, t=(120−36)/72=76t = (120 - 36)/72 = \frac{7}{6}.

python · try it yourself
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 p0+vtp_0 + v t and a circle (c,r)(c, r), what is the coefficient of t2t^2?

  1. v⋅vv \cdot v
  2. 2(d⋅v)2(d \cdot v)
  3. d⋅d−r2d \cdot d - r^2
  4. r2r^2

The quadratic gives t1=−0.7t_1 = -0.7 and t2=0.3t_2 = 0.3. What happened?

  1. No collision
  2. The hit is at t=−0.7t = -0.7
  3. The point started inside the circle and leaves it at t=0.3t = 0.3
  4. The hit is at t=0.3t = 0.3 from outside

Why does checking overlap only at each frame's end miss some collisions?

  1. Because floats are inexact
  2. A fast object can move from one side of a thin target to the other within one frame
  3. Because circles have no area
  4. Because the quadratic formula is slow