skip to content

A sentry turret vanishes from the screen whenever the player jumps onto its top; how can normalizing a vector cause that, and how do you guard against it?

level: seniorimportance: should knowfreq 50%

answer

  1. what is directly overhead
  2. zero divided by zero
  3. NaN spreads and compares false
  4. threshold on squared length, then fallback

basics

~20 s

Directly above the turret, the horizontal aim offset is zero, and normalizing it divides 0 by 0, giving NaN components that poison the turret's orientation and transform, so it typically disappears. Guard with a squared-length check and a fallback direction.

solid answer

~50 s

The turret flattens the offset to the player onto its turning plane, `flat = t - dot(t, up) * up`. With the player on top, `flat` is `(0, 0, 0)`, and normalizing it computes `0 / 0`, or `0 * (1 / 0) = 0 * infinity`; both are NaN in default IEEE 754 arithmetic. The heading becomes NaN, the orientation built from it becomes NaN, every position derived from it follows, and the mesh typically disappears or renders as garbage. NaN also compares false against everything, so range checks silently fail rather than crash. I would confirm it with a debug assertion that vectors written to the transform are finite, then fix it with a safe normalize: compare the squared length against a small threshold and return a caller-chosen fallback, here the last valid heading. I would write the guard so a NaN input also takes the fallback branch.

code

pseudocode · 11 lines
pseudocode
function safeNormalize(v, fallback):
    lenSq = dot(v, v)
    if lenSq > EPS * EPS:              // NaN fails this test too
        return v * (1 / sqrt(lenSq))
    return fallback

// turret aim, every frame
t = playerPos - turretPos
flat = t - dot(t, up) * up
heading = safeNormalize(flat, lastHeading)   // player on top: keep the old heading
lastHeading = heading

go deeper

for a junior

Recall that normalizing divides by the length, so a zero vector has no direction, and that the result is NaN rather than an error in default floating-point arithmetic.

for a middle

Explain how one NaN spreads through every value computed from it, why comparisons with NaN are all false, and where zero vectors arise: arrival, overhead targets, parallel cross products.

for a senior

Diagnose from the symptom: a reproducible geometric coincidence, a vanishing object, no crash. Then show finiteness assertions to find the first bad value and a safe normalize with a caller-chosen fallback and a NaN-proof comparison.

for a principal

Lead-level judgment is a codebase policy: whether the shared normalize asserts in debug builds, takes an explicit fallback argument, and which units its threshold assumes, so degenerate cases are decided once per call site, not discovered in playtests.

## The failure chain 1. The turret aims by flattening the offset to the player onto its turning plane: `t = playerPos - turretPos`, then `flat = t - dot(t, up) * up`. 2. The player lands on top of the turret, directly above its pivot. Now `t` is purely vertical and `flat` is `(0, 0, 0)`. 3. **Normalizing** divides a vector by its length: `flat / length(flat)`, or `flat * (1 / length(flat))`. The length is 0. In default **IEEE 754** floating-point arithmetic, `0 / 0` is **NaN** (not a number), and `1 / 0` is positive infinity, after which `0 * infinity` is NaN as well. Either way every component of the heading is NaN. 4. The turret's orientation is built from that heading, so it is NaN; its world transform is NaN; every vertex the transform touches is NaN. 5. The mesh typically disappears, or renders as stretched garbage; the exact symptom depends on the renderer. Nothing crashes, which is why it looks like a visibility bug rather than a math one. ## Why NaN spreads and hides - **Arithmetic propagates it.** Almost any operation with a NaN operand produces NaN, so one bad heading contaminates everything computed from it, frame after frame if the value is stored. - **Comparisons are false.** `NaN < x`, `NaN > x` and `NaN == x` are all false, so `if distanceSq < rangeSq` neither fires nor errors; the turret just stops doing anything. - **NaN is not equal to itself.** That is the one reliable property for detecting it, though a dedicated finite-value check is clearer. - **It travels.** A NaN position handed to collision or networking code can spread to other objects through every system that reads it. ## Where zero-length vectors come from in game code - A target exactly overhead or underfoot, after removing the vertical component. - A seeker or follower that has arrived: `target - position` is zero. - The difference of two equal positions, such as two spawn points placed on top of each other. - The **cross product of parallel vectors**, which is zero, so normalizing it fails in exactly the same way. - Very small vectors whose squared length underflows to zero, even though the vector itself is not zero. ## Diagnosing it 1. Note the trigger: here, standing directly on the turret. A geometric coincidence that reproduces exactly is a strong hint of a degenerate vector. 2. Add a **debug-build assertion** that every vector written into an orientation or transform is finite, and break on the first failure. 3. Walk back from the assertion to the first operation whose inputs were finite and output was not; it is almost always a normalize, a division or an arccosine. ## Guarding: a safe normalize The fix is a normalize that refuses to divide by a tiny length and asks the caller what to do instead: - **Test the squared length** against a squared threshold, `dot(v, v) > EPS * EPS`, which avoids the square root on the failing path. - **Write the test so the success branch is the guarded one.** If the code says "if `lenSq <= EPS*EPS` return fallback, else divide", a NaN input fails the comparison and falls through to the division. Testing `lenSq > EPS*EPS` before dividing sends NaN to the fallback. - **Let the caller choose the fallback.** For the turret, keep the last valid heading. For a seeker that has arrived, stop steering. A zero vector is rarely the right silent default, because a zero direction can produce a degenerate orientation further on. - **Pick the threshold for the world's scale.** In a world measured in metres, something like `1e-4` (a tenth of a millimetre) is far below anything gameplay cares about and far above rounding noise. The right value depends on units; it is a choice, not a constant. | approach | outcome when v is zero | outcome when v is NaN | |---|---|---| | plain normalize | NaN components | NaN components | | guard `lenSq <= EPS*EPS` returns fallback first | fallback | NaN components | | guard `lenSq > EPS*EPS` before dividing | fallback | fallback | Floating-point details beyond this, such as comparing with relative tolerances or how compiler settings affect NaN checks, are part of floating-point robustness more broadly.

  • Why not make normalize return the zero vector whenever the length is zero?
    It hides the problem one step further on. A zero heading fed into an orientation builder or a look direction is itself degenerate, so the NaN or a collapsed transform appears later and is harder to trace. Only the caller knows the sensible fallback: the previous heading, the current forward, or doing nothing this frame.
  • How would you find which line produced the first NaN in a large codebase?
    Assert finiteness at the boundaries where vectors are stored, such as transforms, physics state and network snapshots, in debug builds, and break on the first failure. From there, step back to the first operation with finite inputs and a non-finite output; it is usually a normalize, a division by a length, or an arccosine of a value just past 1.
  • Why test the squared length rather than the length?
    It skips a square root on every call, and the comparison is equivalent because lengths are non-negative: `length(v) > EPS` exactly when `dot(v, v) > EPS * EPS`. The threshold is squared once, at the call site or as a constant.

  • Dividing zero by zero throws an exception, so the bug would crash instead.
  • A NaN vector compares as zero, so range checks treat the turret as in range.
  • Fixes it by having normalize return the zero vector everywhere, silently.
  • Guards with a less-or-equal threshold test first, letting NaN fall through to the division.
  • Treats the vanishing turret as a rendering or culling bug without checking the transform.