How does an NPC decide whether it can see a target using a vision cone, a sight range and a line-of-sight check?
answer
- cheap tests before the expensive one
- squared distance, no square root
- half the field of view
- cosine threshold, computed once
- ray from the eyes, not the feet
basics
~20 sAn NPC sees a target when three tests pass in cost order: the target is within sight range, inside the cone's half-angle (a dot product against the cosine of that half-angle), and an unobstructed ray reaches it from the NPC's eyes.
solid answer
~50 sI run the cheap tests first. **Range**: compare the squared distance from the eye to the target with `range * range`, so there is no square root. **Angle**: with a unit gaze vector `f` and the unit direction to the target `d`, the target is inside the cone when `dot(f, d) >= cos(halfAngle)`; the cosine is precomputed once, so there is no `acos` per check, and using the full field of view instead of half of it is the classic bug. Only targets that pass both get a **line-of-sight** ray, cast from the eye position rather than the feet to one or more points on the target, ignoring the viewer and the target themselves and any geometry the game treats as see-through. Many games also add a short awareness radius that skips the angle test, so someone crouched right behind the guard can still be noticed.
code
pseudocode · 11 linesfunction canSee(guard, target):
toTarget = target.chestPos - guard.eyePos
distSq = dot(toTarget, toTarget)
if distSq > guard.sightRange * guard.sightRange:
return false // too far: cheapest rejection
if distSq > guard.nearRadius * guard.nearRadius:
dir = toTarget / sqrt(distSq) // safe: distSq > nearRadius^2 >= 0
if dot(guard.eyeForward, dir) < guard.cosHalfAngle:
return false // outside the vision cone
// inside the cone, or close enough that the angle is ignored
return lineOfSight(guard.eyePos, target.chestPos, ignore = [guard, target])go deeper
Recall the three tests and their order: squared distance against squared range, dot product against the cosine of the half-angle, then a ray from the eyes.
Derive why the dot-product test works, show the half-angle bug with numbers, and explain where the ray starts, where it ends and what it ignores.
Talk about line-of-sight policy at scale: several body points, see-through geometry, rays spread across frames, and the playtest symptoms each mistake produces.
Frame the cone as a design contract with players: its shape, its peripheral zone and what blocks sight must be readable and consistent across every enemy type.
## What "seeing" means for an NPC An NPC does not render the scene, so "can the guard see the player?" has to be answered with geometry. The standard answer is three tests, run in order of cost: 1. **Range**: is the target closer than the guard's sight range? 2. **Angle**: is the target inside the **vision cone**, the set of directions within a **half-angle** of the guard's gaze? 3. **Line of sight**: does an unobstructed segment connect the guard's eyes to the target? The first two are a handful of multiplications. The third is a ray query against level geometry, answered by the physics system, and costs far more. Running the cheap tests first means most targets are rejected before any ray is cast. ## Test 1: range without a square root Let `v = targetPoint - eyePos`. The distance is `sqrt(dot(v, v))`, but comparing `dot(v, v) <= range * range` gives the same verdict without the square root, because both sides are non-negative and squaring preserves order for non-negative numbers. ## Test 2: the cone as a dot product For unit vectors `f` (the gaze direction) and `d` (the direction to the target), `dot(f, d) = cos(theta)`, where `theta` is the angle between them. Between 0 and 180 degrees cosine is strictly decreasing, so `theta <= halfAngle` holds exactly when `dot(f, d) >= cos(halfAngle)`. Precompute `cosHalfAngle = cos(fieldOfView / 2)` once per guard. | Field of view | Half-angle | Threshold `cos(halfAngle)` | |---|---|---| | 90 degrees | 45 degrees | about 0.707 | | 120 degrees | 60 degrees | 0.5 | | 180 degrees | 90 degrees | 0 | The table exposes two classic bugs. Comparing against `cos(fieldOfView)` instead of the half-angle gives a 120-degree guard a threshold of -0.5, which is really a 240-degree cone. Testing `dot > 0` is right only for a 180-degree field of view. Calling `acos` on every check is slower and fragile: rounding can push the dot product of two nearly aligned unit vectors slightly above 1, outside the domain of `acos`, unless it is clamped. If you would rather not normalise `v`, the test `dot(f, v) >= cosHalfAngle * length(v)` is equivalent, but it still needs the length. Squaring both sides to avoid that is only valid when both sides are non-negative, so it needs a sign check first. Some games also use separate horizontal and vertical half-angles, so a guard looking ahead notices someone on a balcony above less readily than someone beside it. ## Test 3: line of sight Only targets that pass range and angle get a ray. The physics system answers the query; the perception code decides the **policy**: - **From where**: the eye or head position, not the character's origin at its feet, or a waist-high wall blocks sight it should not. - **To where**: one point such as the chest is cheapest; several points (head, chest, hands, feet) let a partly hidden target count as partly visible. - **Against what**: the ray ignores the viewer and the target themselves and tests only the geometry the game says blocks sight, so glass hides no one while smoke or dense foliage might. - **How often**: visibility rarely changes from one frame to the next, so checks can be spread across frames and the result cached. ## Variations and mistakes Real games bend the pure cone in a few common ways: - A short **awareness radius** around the guard that skips the angle test, so someone crouched right behind it can still be noticed. - A narrow central cone at full sensitivity plus a wider **peripheral** cone that only notices movement or fills a detection meter slowly. - Range and angle that change with alert level: a searching guard looks wider and further than one on a bored patrol. Defects that show up in playtests: - Guards that see behind themselves: the full field of view was used where the half-angle belongs. - Guards blind to players on stairs: the gaze was taken from the body rather than the head, or a flat 2D angle test was mixed with 3D positions. - Guards that see through a chain-link fence but not through a window, or the reverse: the set of geometry the sight ray tests does not match what the art shows. - Frame spikes when many guards look at once: rays are cast before the cheap tests, or every guard casts every frame.
- Why compare the dot product with the cosine of the half-angle instead of computing the angle with acos?Cosine is strictly decreasing between 0 and 180 degrees, so `theta <= halfAngle` is exactly `cos(theta) >= cos(halfAngle)`, and `cos(theta)` is the dot product of the two unit vectors. The threshold is computed once per guard, so each check is a dot product and a comparison. `acos` costs more and fails on rounding: two nearly aligned unit vectors can give a dot product just above 1, outside its domain, unless you clamp.
- How would you give a guard sharp central vision and weaker peripheral vision?Use two cones. The inner cone, say 60 degrees wide, detects at full rate; the outer one, say 140 degrees, detects only moving targets or fills a detection meter at a fraction of the rate. A smoother version scales sensitivity by how far the dot product sits between the outer and inner thresholds. Either way the output is a sensitivity value the detection logic consumes, not a separate yes or no.
- What should a sight ray treat as blocking?Only what the player would agree hides them: walls, closed doors and solid props, but not glass, thin railings or chain-link fences, and perhaps smoke or foliage as partial cover. The physics system supplies the filtering mechanism; the perception design decides which category of geometry blocks sight. When that category drifts from what the art shows, players see guards spotting them through walls or missing them through windows.
- Compare the dot product against the cosine of the full field of view.
- A positive dot product means the target is inside any vision cone.
- Cast the line-of-sight ray first, then do the range and angle tests.
- Cast the sight ray from the character's origin at its feet.
- If one ray to the chest is blocked, the target is fully hidden.