Length, Direction and the Dot Product
A gull swoops toward the drone. Should the warning light flash? Only if the gull is in front, where the pilot has no time to dodge. "In front of" sounds like a job for angles and trigonometry, but games answer it with two multiplications and an addition: the dot product.
The rule
Dot product sign: positive ahead, zero beside, negative behind.
Three tools, in the order you'll reach for them.
Length. An arrow's length, its magnitude, comes from Pythagoras: . The arrow from the drone to the crate, , is m long. The distance between two points is the length of the arrow between them.
Direction. Divide an arrow by its own length and you get a unit vector: length 1, pointing the same way. . A unit vector separates which way from how far. To fly toward the crate at 5 m/s, the velocity is .
Dot product. Multiply matching components and add: . For two unit vectors, the result is the cosine of the angle between them: 1 when they point the same way, 0 at right angles, −1 when they point opposite ways. For any two arrows, the sign alone says ahead, beside or behind.
The shortcut
"Is it in front?" needs no angles and no square roots: dot the facing direction with (target − self) and read the sign. Only for a cone, such as a camera's view, do you normalise both arrows and compare with a cosine: a target is inside a cone of half-angle when the dot of the two unit vectors is at least .
Facing and offset
The drone at (2, 11) faces (0.6, −0.8), down and to the right. The boat at (14, 2) sits at offset (14 − 2, 2 − 11) = (12, −9).
Two traps. Comparing a dot of un-normalised arrows with a cosine gives nonsense, because the lengths inflate the result. And for "is it within 10 m?" skip the square root entirely: compare the squared length with .
Drills
Answer fast — trust the rule.
What is the unit vector of (0, −4)?
Two unit vectors have a dot product of 0. How do they point?
For offset (dx, dy), which test correctly says "the crate is within 10 m" without a square root?
Remember
- Length is Pythagoras; divide by it to get a unit direction.
- Dot the facing with (target − self): positive ahead, zero beside, negative behind.
- For cones, normalise both and compare with the cosine; for distances, compare squares.
