skip to content

How do you turn an enemy's world-space head position into pixel coordinates to place a floating health bar over it?

level: middleimportance: should knowfreq 50%

answer

  1. same chain the renderer walks
  2. view-projection with w = 1
  3. check w before dividing
  4. NDC y up, pixel y down
  5. scale by one over w

basics

~20 s

Multiply the head position (w = 1) by view-projection, hide the bar if clip w is not positive, divide by w, then map x to (ndc.x + 1) / 2 * width and y to (1 - ndc.y) / 2 * height.

solid answer

~50 s

Take the enemy's head position plus a small world-space offset and compute `clip = viewProj * (pos, 1)` with column vectors. If `clip.w <= 0` the point is at or behind the camera: hide the bar, because dividing would mirror it onto the screen. Otherwise divide by `w` to get NDC; if `x` or `y` falls outside `[-1, 1]` it is off screen. Map to pixels with `px = viewportX + (ndc.x + 1) / 2 * width` and `py = viewportY + (1 - ndc.y) / 2 * height`, the `1 - ndc.y` flipping NDC's upward `y` into downward pixel rows. For a perspective camera `clip.w` is the view depth, so scaling the bar by `1 / w` makes it shrink with the enemy, or you keep a fixed pixel size. Project after the camera has moved this frame or the bar lags.

code

pseudocode · 10 lines
pseudocode
function worldToScreen(worldPos, viewProj, viewportX, viewportY, width, height):
    clip = viewProj * Vector4(worldPos, 1)
    if clip.w <= 1e-5:                         // at or behind the camera
        return HIDDEN
    ndc = clip.xyz / clip.w
    if abs(ndc.x) > 1 or abs(ndc.y) > 1:
        return OFF_SCREEN(ndc.x, ndc.y)        // caller may clamp to an edge arrow
    px = viewportX + (ndc.x * 0.5 + 0.5) * width
    py = viewportY + (0.5 - ndc.y * 0.5) * height   // pixel rows grow downwards
    return ON_SCREEN(px, py, clip.w)           // clip.w = view depth, for scaling

go deeper

for a junior

Recall the steps: view-projection with w = 1, divide by w, then scale NDC to the viewport with a y flip.

for a middle

Explain why the w test must precede the divide, how the y flip arises, and how 1 / w gives the size a bar should have at a distance.

for a senior

Diagnose shipped symptoms: bars mirrored for enemies behind you, bars lagging a frame behind camera motion, offsets wrong on high-density displays or in split screen.

for a principal

Own one shared world-to-screen helper for every marker, icon and damage number, with defined behaviour behind the camera and off screen, so each feature does not reinvent it.

## The conventions this answer assumes The health bar is a 2D widget drawn on top of the 3D view, so its position must come from walking the enemy's head through the same chain of spaces the renderer uses. This answer assumes **column vectors** (`clip = P * V * p`), a **perspective** camera, NDC with `x` and `y` in `[-1, 1]` and `+y` up, and **pixel coordinates** with the origin at the viewport's top-left and rows growing downwards. ## The steps 1. Take the anchor point: the head position, or the enemy's root plus a world-space offset of roughly its height. Use `w = 1`, because it is a point and the view matrix's translation must apply. 2. Transform it once with the camera's combined **view-projection** matrix: `clip = viewProj * (x, y, z, 1)`. 3. Reject points at or behind the camera: if `clip.w <= epsilon`, hide the bar. 4. Divide: `ndc = clip.xyz / clip.w`. 5. Reject or clamp points outside the screen: `abs(ndc.x) > 1` or `abs(ndc.y) > 1`. 6. Map to pixels: `px = viewportX + (ndc.x * 0.5 + 0.5) * width` and `py = viewportY + (0.5 - ndc.y * 0.5) * height`. A worked example: camera at the origin looking down `-z` (so the view matrix is the identity), vertical field of view 90 degrees, aspect 16:9, a 1920 by 1080 viewport, head at `(2, 1, -4)`. The projection gives `clip.x = 0.5625 * 2 = 1.125`, `clip.y = 1`, `clip.w = 4`. So `ndc = (0.28125, 0.25)`, and the pixel is `(0.640625 * 1920, 0.375 * 1080) = (1230, 405)`: right of centre and above it, as expected for a point up and to the right. ## Points behind the camera For a point behind a perspective camera, `clip.w` is negative. Dividing by it flips the signs of `x` and `y`, so the result is the point **mirrored through the screen centre**, and often its `x` and `y` land inside `[-1, 1]` and pass the off-screen test. That is the classic bug: an enemy behind the player shows a health bar floating in front of them. The `w` check must come **before** the divide; testing NDC `x` and `y` afterwards cannot catch it. ## Off-screen and edge indicators - Hiding off-screen bars is the simple choice. - For an **edge arrow** pointing at an off-screen enemy, take the direction from the screen centre to the NDC point and clamp it to the screen rectangle. - For an enemy behind the camera the NDC direction is mirrored, so negate it, or compute the direction from the view-space `x` and `y` instead of NDC. ## Size and stability - For a perspective camera `clip.w` equals the depth in front of the camera along its view direction, so a bar scaled by `k / clip.w` shrinks exactly like the enemy. Many games instead keep a fixed pixel size, sometimes clamped between a minimum and a maximum. - **Project after the camera update** for the frame. Using last frame's view-projection makes the bar trail the enemy whenever the camera moves. - If the UI is laid out at a different resolution from the 3D viewport (a scaled canvas, a high-density display), convert pixel coordinates into UI units with the same scale factor the UI uses. - In split screen, each player's bars use that player's view-projection and viewport offset. - Rounding the final position to whole pixels stops thin bars shimmering as they move. - An enemy hidden behind a wall still projects to a valid pixel. Whether to hide its bar is a visibility decision, made with a line-of-sight ray or a depth comparison, not something the projection answers. ## Why not just ask the renderer Rendering the bar as a camera-facing quad in the world is the alternative. It sorts and occludes with the scene automatically, but it cannot keep a constant pixel size without the same `1 / w` reasoning, and it is drawn in a different pass from the rest of the UI. Projecting a single point per enemy is cheap, and the same function serves minimap markers, objective icons and damage numbers.

  • Why does an off-screen test on NDC x and y not catch an enemy standing behind the camera?
    Behind the camera `clip.w` is negative, so the divide flips `x` and `y` and the point lands mirrored through the screen centre, frequently well inside `[-1, 1]`. The x and y test sees a valid on-screen position. Testing `clip.w` before dividing is the direct way to tell in front from behind.
  • How would you keep the health bar exactly 40 pixels above the enemy's head at every distance?
    Project the head point itself, then apply the 40-pixel offset in screen space, subtracting from `py`. A world-space offset projects to fewer pixels as the enemy moves away, because its screen size scales with `1 / w`. Mixing the two, a small world offset plus a screen offset, keeps the bar clear of helmets at close range.

Tracing a mountain onto a window pane while keeping your head still: the mark goes where the line from your eye to the peak crosses the glass. A peak behind you never crosses that pane, so there is nothing honest to draw.

  • Checking that NDC x and y are inside -1 to 1 hides enemies behind the camera.
  • Clip coordinates can be used as screen positions without dividing by w.
  • NDC y and pixel y point the same way.
  • The enemy's position should be transformed with w = 0.
  • Projecting before the camera update makes no visible difference.