In a strategy game, how do you turn a mouse click's pixel position into a world-space ray for selecting the unit under the cursor?
answer
- run the chain backwards
- pixel to NDC with a y flip
- two depths, one inverse
- divide by w again
- parallel rays when orthographic
basics
~20 sConvert the click to NDC, build two NDC points at near and far depth, multiply both by the inverse view-projection matrix, divide each by its w, and use the near point as origin and the normalised difference as direction.
solid answer
~50 sRun the projection chain backwards. With the pixel origin at the viewport's top-left, `ndc.x = 2 * (px - viewportX) / width - 1` and `ndc.y = 1 - 2 * (py - viewportY) / height`, the second flipping pixel rows into NDC's upward `y`. Form two homogeneous points at the near and far NDC depth of your convention, `(ndc.x, ndc.y, zNear, 1)` and `(ndc.x, ndc.y, 1, 1)`, multiply each by `inverse(P * V)` and **divide each by its own w**. The ray starts at the near point and points along `normalize(far - near)`. That works for perspective and orthographic cameras alike; for orthographic all rays are parallel, so the origin must come from the near point, not the camera position. The ray is then tested against units' bounds or the terrain to find what was clicked.
code
pseudocode · 8 linesfunction screenPointToRay(px, py, viewportX, viewportY, width, height, invViewProj, ndcNearZ):
ndcX = 2 * (px - viewportX) / width - 1
ndcY = 1 - 2 * (py - viewportY) / height // pixel rows grow downwards
nearH = invViewProj * Vector4(ndcX, ndcY, ndcNearZ, 1) // ndcNearZ is -1 or 0 by convention
farH = invViewProj * Vector4(ndcX, ndcY, 1, 1)
nearW = nearH.xyz / nearH.w // undo the perspective divide
farW = farH.xyz / farH.w
return Ray(origin = nearW, direction = normalize(farW - nearW))go deeper
Recall the steps: pixel to NDC with a y flip, two depths through the inverse view-projection, divide by w, subtract for the direction.
Explain why a click is a ray, why the divide by w is still needed after the inverse, and why orthographic rays need an unprojected origin.
Diagnose wrong selections from the symptom: vertical mirroring, a constant offset from a UI panel, a scale error on high-density displays, a lag while the camera scrolls.
Make one picking function shared by selection, placement and debug tools, with documented viewport and unit conventions, so each feature does not carry its own variant of the same bugs.
## Why picking starts with a ray A pixel on screen is not a point in the world: every world point on one line from the camera through that pixel projects onto it. **Unprojecting** a click therefore yields a **ray**, an origin plus a direction, and the game then asks which unit or terrain cell that ray hits first. Interviewers like this because it requires the whole chain of spaces in reverse. This answer assumes **column vectors**, a combined view-projection `VP = P * V`, 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. ## From pixel to NDC 1. Make the click relative to the 3D viewport, not the window: `sx = px - viewportX`, `sy = py - viewportY`. Strategy games often reserve part of the window for a side panel or minimap, so the two differ. 2. Map to NDC: `ndc.x = 2 * sx / width - 1`, `ndc.y = 1 - 2 * sy / height`. 3. Optionally add half a pixel to `sx` and `sy` to aim at the pixel centre. For a click at `(320, 180)` in a 1280 by 720 viewport, `ndc = (-0.5, 0.5)`: left of centre and above it. ## From NDC back to world 1. Build two homogeneous points with that `x` and `y`: one at the **near** depth, `-1` or `0` depending on the NDC depth convention, and one at the **far** depth, `1`. 2. Multiply both by `inverse(VP)`. Note `inverse(P * V) = inverse(V) * inverse(P)`. 3. **Divide each result by its own `w`.** For a perspective camera the two `w` values differ, so skipping this produces scaled copies of the points that generally do not lie on the pixel's line. 4. `origin = nearWorld`, `direction = normalize(farWorld - nearWorld)`. For a perspective camera any two distinct depths along the pixel's line give the same ray, so using the wrong depth convention mostly shifts the origin slightly along it. The divide by `w`, the `y` flip and the viewport offset are what break picking. ## Perspective vs orthographic cameras | | Perspective | Orthographic | |---|---|---| | Rays for different pixels | all pass through the camera position | parallel, one per pixel | | Valid origin | camera position or near point | near point only | | Direction | depends on the pixel | the camera's forward for every pixel | | Divide by `w` after the inverse | required, `w` varies | harmless, `w` stays 1 | Using the inverse matrix for both cases means one function serves an angled strategy camera and a strictly top-down orthographic one. ## A cheaper equivalent for perspective Without inverting a 4x4 matrix, build the direction in view space from the field of view: `dirView = (ndc.x * aspect * tan(fovY / 2), ndc.y * tan(fovY / 2), -1)` for a right-handed camera looking down `-z`. Rotate it into world space with the camera's rotation, treating it as a direction (`w = 0`), and start the ray at the camera position. This is the same line, derived from the similar triangles that built the projection. ## Bugs that select the wrong unit - **No divide by `w`**: the two points are scaled copies, so the ray is skewed by an amount that grows with the camera's distance from the world origin; a test with the camera at the origin can look correct. - **No `y` flip**: clicks select units mirrored vertically about the screen centre. - **Window size instead of viewport size or offset**: picking is shifted or scaled whenever a UI panel or split screen shrinks the 3D view. - **Mouse in logical units, viewport in physical pixels** on a high-density display: clicks land at a multiple of the intended position. - **Stale matrix**: picking with last frame's view-projection while the camera edge-scrolls selects the unit that used to be under the cursor. - **Wrong inverse order**: `inverse(V) * inverse(P)` is correct; `inverse(P) * inverse(V)` is not. ## What happens next The ray itself does not know about units. The game intersects it with each candidate's bounding volume or collision shape, or hands it to a physics raycast with a filter for selectable objects, and takes the nearest hit. For a click-to-move order on flat ground, intersecting the same ray with the ground plane gives the destination.
- How would you select every unit inside a drag rectangle rather than under one click?The usual approach projects each selectable unit's position to screen space, skips units behind the camera, and tests the pixel against the rectangle, which is cheap at typical unit counts. The alternative unprojects the rectangle's four corners into rays and builds a selection volume from the four side planes, then tests units against it; that handles large units whose centres sit just outside the rectangle.
- Why can clicks land at a multiple or a fraction of the intended position on a high-density display?The mouse position is often reported in logical units while the 3D viewport is sized in physical pixels, or the reverse. Normalising with one and reading the other scales every click by the display's scale factor, or its reciprocal. Convert both to the same unit before computing NDC, ideally by dividing the click by the size of the space it was reported in.
- When is the camera position not a valid ray origin for picking?With an orthographic camera every pixel's ray is parallel to the camera's forward and passes through a different point, so a ray from the camera position would always pick whatever is under the screen centre. Taking the origin from the unprojected near-plane point works for both projections.
- Multiplying by the inverse view-projection gives world positions without a divide by w.
- Pixel y can be used as NDC y without flipping it.
- A click maps to a single world point rather than a ray.
- Every picking ray can start at the camera position, even for an orthographic camera.
- The window size is always the right width and height for computing NDC.