TExcelTAD
Home › Pre-Calculus, Geometry & Trigonometry › Trig in Games: Aiming and Circular Motion

Trig in Games: Aiming and Circular Motion

Three bits of trigonometry run in almost every game: turning a character or turret to face a target, moving something around a circle, and aiming ahead of a moving target so the shot actually hits. Each one is a few lines of code once you know which formula to use, and each one has a classic bug that this lesson shows you how to avoid.

The angle to a target

The direction from a turret at (x0,y0)(x_0, y_0) to a target at (x,y)(x, y) is the vector (dx,dy)=(x−x0,y−y0)(dx, dy) = (x - x_0, y - y_0). Its angle from the positive xx-axis is atan2⁡(dy,dx)\operatorname{atan2}(dy, dx), not atan⁡(dy/dx)\operatorname{atan}(dy/dx): atan only returns angles between −90° and 90° and cannot tell (1,1)(1, 1) from (−1,−1)(-1, -1), while atan2 looks at both signs and returns the full range (−180∘,180∘](-180^\circ, 180^\circ] (inverse trig functions, atan2).

(dx,dy)=(−3,3)atan⁡(3/−3)=atan⁡(−1)=−45∘wrong quadrantatan2⁡(3,−3)=135∘correct\begin{aligned} &(dx, dy) = (-3, 3) \qquad && \operatorname{atan}(3/{-3}) = \operatorname{atan}(-1) = -45^\circ && \text{wrong quadrant} \\ & && \operatorname{atan2}(3, -3) = 135^\circ && \text{correct} \end{aligned}

Note: On screens the yy-axis usually points down, so positive angles turn clockwise. The maths is the same; only the picture flips.

Turning toward it smoothly

Snapping to the target angle looks robotic. Real turrets turn at a maximum rate, say 90° per second. Each frame, compute the signed shortest difference between the target angle and the current heading, clamp it to the allowed step, and add it.

The classic bug: from a heading of 350° to a target at 10°, the naive difference 10−350=−340∘10 - 350 = -340^\circ makes the turret spin the long way round. Wrap the difference into (−180∘,180∘](-180^\circ, 180^\circ] first:

diff=((target−heading+180) mod 360)−180((10−350+180) mod 360)−180=20∘\text{diff} = ((\text{target} - \text{heading} + 180) \bmod 360) - 180 \qquad ((10 - 350 + 180) \bmod 360) - 180 = 20^\circ
python · try it yourself
import math

def angle_to(src, dst):
    return math.degrees(math.atan2(dst[1] - src[1], dst[0] - src[0]))

def shortest_diff(target, heading):
    return (target - heading + 180) % 360 - 180

def turn_toward(heading, target, max_step):
    d = shortest_diff(target, heading)
    d = max(-max_step, min(max_step, d))
    return (heading + d) % 360

print(f"{angle_to((0, 0), (-3, 3)):.1f}  atan gives {math.degrees(math.atan(3 / -3)):.1f}")
print("naive:", 10 - 350, " shortest:", shortest_diff(10, 350))

heading, target, rate, dt = 300.0, angle_to((0, 0), (4, 2)) % 360, 90.0, 0.25
print(f"target heading {target:.2f}")
for frame in range(1, 6):
    heading = turn_toward(heading, target, rate * dt)
    print(f"frame {frame}: heading {heading:6.2f}")
135.0  atan gives -45.0
naive: -340  shortest: 20
target heading 26.57
frame 1: heading 322.50
frame 2: heading 345.00
frame 3: heading   7.50
frame 4: heading  26.57
frame 5: heading  26.57

Python's % always returns a result with the sign of the divisor, so (x + 180) % 360 - 180 lands in [−180,180)[-180, 180). In C, C++, Java or JavaScript, % keeps the sign of the dividend; there you must add 360 before taking the remainder, or use a helper like fmod plus a fix-up.

Circular motion

A moon orbiting a planet at centre (cx,cy)(c_x, c_y) with radius rr and period TT (seconds per lap) is at

θ(t)=θ0+ωtω=2π/T(angular speed, radians per second)x(t)=cx+rcos⁡θ(t)y(t)=cy+rsin⁡θ(t)\begin{aligned} \theta(t) &= \theta_0 + \omega t && \omega = 2\pi / T \quad \text{(angular speed, radians per second)} \\ x(t) &= c_x + r\cos\theta(t) \\ y(t) &= c_y + r\sin\theta(t) \end{aligned}

These are the parametric equations of a circle. Its velocity is always tangent to the circle, (−rωsin⁡θ, rωcos⁡θ)(-r\omega\sin\theta,\ r\omega\cos\theta), with constant speed rωr\omega. Use radians inside cos and sin (angles and radians). Computing θ\theta from the total time tt, rather than adding a small angle every frame, also keeps the orbit from drifting through accumulated rounding error.

Leading a moving target

A turret at the origin fires bullets at speed ss. The target is at PP and moves with constant velocity VV. We want the time tt at which a bullet and target meet. The target is then at P+VtP + Vt, at distance stst from the turret (that is how far the bullet flew):

∣P+Vt∣=st(P+Vt)⋅(P+Vt)=s2t2(V⋅V−s2)t2+2(P⋅V)t+P⋅P=0\begin{aligned} \lvert P + Vt \rvert &= st \\ (P + Vt) \cdot (P + Vt) &= s^2 t^2 \\ (V \cdot V - s^2)t^2 + 2(P \cdot V)t + P \cdot P &= 0 \end{aligned}

That is a quadratic in tt, just like collision timing. Take the smallest positive root and aim at the intercept point P+VtP + Vt. If there is no positive root, the target is too fast to hit.

python · try it yourself
import math
import matplotlib.pyplot as plt

def lead_time(P, V, s):
    a = V[0]**2 + V[1]**2 - s * s
    b = 2 * (P[0] * V[0] + P[1] * V[1])
    c = P[0]**2 + P[1]**2
    if abs(a) < 1e-12:                         # bullet speed = target speed
        return -c / b if b < 0 else None
    disc = b * b - 4 * a * c
    if disc < 0:
        return None
    roots = [(-b - math.sqrt(disc)) / (2 * a), (-b + math.sqrt(disc)) / (2 * a)]
    positive = [t for t in roots if t > 0]
    return min(positive) if positive else None

P, V, s = (30.0, 10.0), (-4.0, 3.0), 12.0
t = lead_time(P, V, s)
aim = (P[0] + V[0] * t, P[1] + V[1] * t)
print(f"hit after {t:.4f} s at ({aim[0]:.3f}, {aim[1]:.3f})")
print(f"aim angle {math.degrees(math.atan2(aim[1], aim[0])):.2f} deg, "
      f"naive angle {math.degrees(math.atan2(P[1], P[0])):.2f} deg")
print(f"bullet distance {s * t:.3f} = |aim| {math.hypot(*aim):.3f}")

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot([P[0], aim[0]], [P[1], aim[1]], "o-", color="tab:red", label="target path")
ax.plot([0, aim[0]], [0, aim[1]], color="tab:blue", label="bullet path")
ax.plot([0, P[0]], [0, P[1]], ":", color="gray", label="naive aim")
ax.plot(0, 0, "ks", label="turret"); ax.set_aspect("equal"); ax.legend(loc="lower right")
hit after 2.2396 s at (21.042, 16.719)
aim angle 38.47 deg, naive angle 18.43 deg
bullet distance 26.875 = |aim| 26.875

Aiming straight at the target (the dotted line) would miss: by the time the bullet arrives, the target has moved up and to the left.

In software

  • AI aiming and homing missiles: atan2 plus a turn-rate clamp; homing missiles re-aim every frame.
  • Cameras: an orbit camera is circular motion around the player, with angles driven by the mouse.
  • UI: radial menus place items at angle 2πk/n2\pi k/n; loading spinners rotate by ωt\omega t.
  • Rotation in general: the same cos/sin pair builds the 2D rotation matrix (rotation in 2D, transformations).

Exercises

Exercise 1: The right quadrant

A guard at (5,5)(5, 5) sees an intruder at (2,1)(2, 1). What angle (in degrees, from the positive xx-axis) should the guard face? What does atan⁡(dy/dx)\operatorname{atan}(dy/dx) give instead?

Answer

atan2⁡(−4,−3)≈−126.87∘\operatorname{atan2}(-4, -3) \approx -126.87^\circ (that is 233.13°); atan⁡(−4/−3)=atan⁡(4/3)≈53.13∘\operatorname{atan}(-4/{-3}) = \operatorname{atan}(4/3) \approx 53.13^\circ, the opposite direction.

Solution
dx=2−5=−3,dy=1−5=−4atan⁡(dy/dx)=atan⁡(4/3)≈53.13∘points up-right: wrongatan2⁡(−4,−3)=53.13∘−180∘=−126.87∘points down-left: right\begin{aligned} &dx = 2 - 5 = -3, \quad dy = 1 - 5 = -4 \\ &\operatorname{atan}(dy/dx) = \operatorname{atan}(4/3) \approx 53.13^\circ && \text{points up-right: wrong} \\ &\operatorname{atan2}(-4, -3) = 53.13^\circ - 180^\circ = -126.87^\circ && \text{points down-left: right} \end{aligned}
python · try it yourself
import math
print(round(math.degrees(math.atan2(-4, -3)), 2), round(math.degrees(math.atan(-4 / -3)), 2))
-126.87 53.13

Exercise 2: Shortest turn

A ship faces 20°. Which way, and how far, should it turn to face 250°?

Answer

Turn −130° (clockwise, 130°), not +230°.

Solution
diff=((250−20+180) mod 360)−180=(410 mod 360)−180=50−180=−130\text{diff} = ((250 - 20 + 180) \bmod 360) - 180 = (410 \bmod 360) - 180 = 50 - 180 = -130

Check: 20∘−130∘=−110∘20^\circ - 130^\circ = -110^\circ, which is the same direction as 250°. ✓

Exercise 3: Where is the moon?

A moon orbits (100,50)(100, 50) at radius 40 with a period of 8 s, starting at angle 0. Where is it at t=3 st = 3\ \text{s}?

Answer

θ=3π/4\theta = 3\pi/4, position ≈(71.716,78.284)\approx (71.716, 78.284)

Solution
ω=2π/8=π/4 per second,θ=3⋅π/4=135∘x=100+40cos⁡135∘=100−40⋅(2/2)=100−202≈71.716y=50+40sin⁡135∘=50+202≈78.284\begin{aligned} &\omega = 2\pi/8 = \pi/4 \text{ per second}, \quad \theta = 3 \cdot \pi/4 = 135^\circ \\ &x = 100 + 40\cos 135^\circ = 100 - 40 \cdot (\sqrt{2}/2) = 100 - 20\sqrt{2} \approx 71.716 \\ &y = 50 + 40\sin 135^\circ = 50 + 20\sqrt{2} \approx 78.284 \end{aligned}
python · try it yourself
import math
theta = 2 * math.pi / 8 * 3
print(round(100 + 40 * math.cos(theta), 3), round(50 + 40 * math.sin(theta), 3))
71.716 78.284

Exercise 4: Lead by hand

A turret at the origin fires bullets at 5 units/s. A drone is at (10,0)(10, 0) and flies with velocity (0,3)(0, 3). When does a bullet hit it, and where should the turret aim?

Answer

t=2.5 st = 2.5\ \text{s}; aim at (10,7.5)(10, 7.5), an angle of about 36.87°.

Solution
V⋅V−s2=9−25=−162(P⋅V)=2(10⋅0+0⋅3)=0P⋅P=100−16t2+100=0  ⟹  t2=6.25  ⟹  t=2.5aim=(10,0)+2.5⋅(0,3)=(10,7.5)\begin{aligned} &V \cdot V - s^2 = 9 - 25 = -16 \\ &2(P \cdot V) = 2(10 \cdot 0 + 0 \cdot 3) = 0 \\ &P \cdot P = 100 \\ &-16t^2 + 100 = 0 \;\Longrightarrow\; t^2 = 6.25 \;\Longrightarrow\; t = 2.5 \\ &\text{aim} = (10, 0) + 2.5 \cdot (0, 3) = (10, 7.5) \end{aligned}

Check: the bullet flies 5⋅2.5=12.55 \cdot 2.5 = 12.5, and ∣(10,7.5)∣=100+56.25=12.5\lvert (10, 7.5) \rvert = \sqrt{100 + 56.25} = 12.5. ✓ The angle is atan2⁡(7.5,10)≈36.87∘\operatorname{atan2}(7.5, 10) \approx 36.87^\circ (a 3-4-5 triangle).

Test yourself

Why use atan2⁡(dy,dx)\operatorname{atan2}(dy, dx) instead of atan⁡(dy/dx)\operatorname{atan}(dy / dx)?

  1. atan2 is faster
  2. atan2 uses the signs of both dydy and dxdx to return the correct quadrant, and handles dx=0dx = 0
  3. atan returns degrees
  4. atan2 works only for positive numbers

Heading 340°, target 30°. What is the shortest signed turn?

  1. −310°
  2. +30°
  3. +50°
  4. −50°

An orbit has radius 3 and period 2 s. What is its speed?

  1. 3π3\pi units/s
  2. 6 units/s
  3. 1.5 units/s
  4. 6π6\pi units/s