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 to a target at is the vector . Its angle from the positive -axis is , not : atan only returns angles between −90° and 90° and cannot tell from , while atan2 looks at both signs and returns the full range (inverse trig functions, atan2).
Note: On screens the -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 makes the turret spin the long way round. Wrap the difference into first:
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 . 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 with radius and period (seconds per lap) is at
These are the parametric equations of a circle. Its velocity is always tangent to the circle, , with constant speed . Use radians inside cos and sin (angles and radians). Computing from the total time , 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 . The target is at and moves with constant velocity . We want the time at which a bullet and target meet. The target is then at , at distance from the turret (that is how far the bullet flew):
That is a quadratic in , just like collision timing. Take the smallest positive root and aim at the intercept point . If there is no positive root, the target is too fast to hit.
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:
atan2plus 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 ; loading spinners rotate by .
- 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 sees an intruder at . What angle (in degrees, from the positive -axis) should the guard face? What does give instead?
Answer
(that is 233.13°); , the opposite direction.
Solution
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
Check: , which is the same direction as 250°. ✓
Exercise 3: Where is the moon?
A moon orbits at radius 40 with a period of 8 s, starting at angle 0. Where is it at ?
Answer
, position
Solution
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 and flies with velocity . When does a bullet hit it, and where should the turret aim?
Answer
; aim at , an angle of about 36.87°.
Solution
Check: the bullet flies , and . ✓ The angle is (a 3-4-5 triangle).
Test yourself
Why use instead of ?
- atan2 is faster
- atan2 uses the signs of both and to return the correct quadrant, and handles
- atan returns degrees
- atan2 works only for positive numbers
Heading 340°, target 30°. What is the shortest signed turn?
- −310°
- +30°
- +50°
- −50°
An orbit has radius 3 and period 2 s. What is its speed?
- units/s
- 6 units/s
- 1.5 units/s
- units/s