Screen-to-World Rays
Clicking on a unit in a strategy game, aiming where the mouse points in a twin-stick shooter, placing a building on the terrain: all of these run the pipeline backwards. A pixel is not a single 3D point (depth was thrown away), it is a whole line of points. So the answer to "what is under the mouse?" is a ray: an origin and a direction, which you then intersect with the scene.
Unprojecting
Undo each step in reverse order:
- pixel → NDC:
ndc.x = 2 * px / width - 1,ndc.y = 1 - 2 * py / height - NDC → world: multiply
(ndc.x, ndc.y, z, 1)byinverse(projection * view), then divide by w. - Do it twice, once at the near plane (
z = -1) and once at the far plane (z = 1). The ray goes from the near point toward the far point.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numbers>
#include <utility>
struct Vec3 { double x, y, z; };
struct Mat4 { double m[4][4]{}; };
Mat4 operator*(const Mat4& A, const Mat4& B) {
Mat4 R;
for (int r = 0; r < 4; r++) for (int c = 0; c < 4; c++) for (int k = 0; k < 4; k++) R.m[r][c] += A.m[r][k] * B.m[k][c];
return R;
}
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
Vec3 normalize(Vec3 v) { double l = std::sqrt(dot(v, v)); return {v.x / l, v.y / l, v.z / l}; }
Mat4 perspective(double fovY, double aspect, double n, double f) {
double t = 1 / std::tan(fovY / 2); Mat4 p;
p.m[0][0] = t / aspect; p.m[1][1] = t;
p.m[2][2] = (f + n) / (n - f); p.m[2][3] = 2 * f * n / (n - f); p.m[3][2] = -1;
return p;
}
Mat4 lookAt(Vec3 eye, Vec3 target, Vec3 up) {
Vec3 f = normalize(target - eye), r = normalize(cross(f, up)), u = cross(r, f);
Mat4 v;
v.m[0][0] = r.x; v.m[0][1] = r.y; v.m[0][2] = r.z; v.m[0][3] = -dot(r, eye);
v.m[1][0] = u.x; v.m[1][1] = u.y; v.m[1][2] = u.z; v.m[1][3] = -dot(u, eye);
v.m[2][0] = -f.x; v.m[2][1] = -f.y; v.m[2][2] = -f.z; v.m[2][3] = dot(f, eye);
v.m[3][3] = 1;
return v;
}
bool inverse(const Mat4& in, Mat4& out) { // Gauss-Jordan, from the Inverse lesson
double a[4][8];
for (int r = 0; r < 4; r++) for (int c = 0; c < 8; c++) a[r][c] = c < 4 ? in.m[r][c] : (c - 4 == r);
for (int col = 0; col < 4; col++) {
int p = col;
for (int r = col + 1; r < 4; r++) if (std::fabs(a[r][col]) > std::fabs(a[p][col])) p = r;
if (std::fabs(a[p][col]) < 1e-12) return false;
for (int c = 0; c < 8; c++) std::swap(a[col][c], a[p][c]);
double d = a[col][col];
for (int c = 0; c < 8; c++) a[col][c] /= d;
for (int r = 0; r < 4; r++) if (r != col) { double f = a[r][col]; for (int c = 0; c < 8; c++) a[r][c] -= f * a[col][c]; }
}
for (int r = 0; r < 4; r++) for (int c = 0; c < 4; c++) out.m[r][c] = a[r][c + 4];
return true;
}
Vec3 unproject(const Mat4& invVP, double nx, double ny, double nz) {
double in[4] = {nx, ny, nz, 1}, o[4] = {};
for (int r = 0; r < 4; r++) for (int c = 0; c < 4; c++) o[r] += invVP.m[r][c] * in[c];
return {o[0] / o[3], o[1] / o[3], o[2] / o[3]}; // divide by w!
}
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec3 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ", " << z0(v.z) << ")"; }
int main() {
std::cout << std::fixed << std::setprecision(3);
const double W = 800, H = 600;
Vec3 eye{0, 10, 10}; // a strategy camera looking down at 45 degrees
Mat4 vp = perspective(std::numbers::pi / 3, W / H, 0.1, 200) * lookAt(eye, {0, 0, 0}, {0, 1, 0});
Mat4 invVP;
inverse(vp, invVP);
double clicks[][2] = {{400, 300}, {600, 300}, {400, 500}};
for (auto& c : clicks) {
double nx = 2 * c[0] / W - 1, ny = 1 - 2 * c[1] / H;
Vec3 nearP = unproject(invVP, nx, ny, -1), farP = unproject(invVP, nx, ny, 1);
Vec3 dir = normalize(farP - nearP);
// Intersect with the ground plane y = 0: origin.y + t * dir.y = 0
double t = -nearP.y / dir.y;
Vec3 hit{nearP.x + dir.x * t, 0, nearP.z + dir.z * t};
std::cout << "click (" << int(c[0]) << ", " << int(c[1]) << "): dir " << dir << " hits ground at " << hit << "\n";
}
}click (400, 300): dir (0.000, -0.707, -0.707) hits ground at (0.000, 0.000, 0.000)
click (600, 300): dir (0.359, -0.660, -0.660) hits ground at (5.443, 0.000, 0.000)
click (400, 500): dir (0.000, -0.914, -0.406) hits ground at (0.000, 0.000, 5.559)
The center pixel hits the ground at the point the camera looks at, the origin. A click to the right lands to the right (+x), and a click lower on the screen lands closer to the camera (+z). The last step, intersecting the ray with the ground, is a ray–plane test; the Geometry section covers it and the other ray tests properly.
A cheaper way for the common case
When you know the camera's position, its axes and the vertical FOV, you can build the ray directly, with no matrix inverse. This is also how ray tracers generate their camera rays:
dir = normalize(forward + right * (ndc.x * tan(fov/2) * aspect) + up * (ndc.y * tan(fov/2)))
origin = camera position#include <iostream>
#include <iomanip>
#include <cmath>
#include <numbers>
struct Vec3 { double x, y, z; };
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
Vec3 normalize(Vec3 v) { return v * (1 / std::sqrt(dot(v, v))); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec3 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ", " << z0(v.z) << ")"; }
int main() {
std::cout << std::fixed << std::setprecision(3);
const double W = 800, H = 600, aspect = W / H, tanHalf = std::tan(std::numbers::pi / 6);
Vec3 eye{0, 10, 10};
Vec3 forward = normalize(Vec3{0, 0, 0} - eye);
Vec3 right = normalize(cross(forward, {0, 1, 0}));
Vec3 up = cross(right, forward);
double clicks[][2] = {{400, 300}, {600, 300}, {400, 500}};
for (auto& c : clicks) {
double nx = 2 * c[0] / W - 1, ny = 1 - 2 * c[1] / H;
Vec3 dir = normalize(forward + right * (nx * tanHalf * aspect) + up * (ny * tanHalf));
double t = -eye.y / dir.y;
std::cout << "click (" << int(c[0]) << ", " << int(c[1]) << "): dir " << dir << " hits ground at " << eye + dir * t << "\n";
}
}click (400, 300): dir (0.000, -0.707, -0.707) hits ground at (0.000, 0.000, 0.000)
click (600, 300): dir (0.359, -0.660, -0.660) hits ground at (5.443, 0.000, 0.000)
click (400, 500): dir (0.000, -0.914, -0.406) hits ground at (0.000, 0.000, 5.559)
Same answers, a fraction of the work. Engines give you this as one call: Unity's Camera.ScreenPointToRay, Unreal's APlayerController::DeprojectMousePositionToWorld, Godot's Camera3D.project_ray_origin + project_ray_normal, and Three.js's Raycaster.setFromCamera.
Tip: For an orthographic camera, every ray has the same direction (the camera's forward) and only the origin changes with the pixel. Code that assumes rays start at the camera position silently breaks when a designer switches the camera to orthographic. Unprojecting the near and far points, as in the first example, works for both.
Test yourself
Why is the result of clicking a pixel a ray and not a point?
- Pixels are too small
- The projection threw away depth, so every point along a line maps to that pixel
- Because the screen is 2D and rays are 2D
- Rays are faster to store
After multiplying an NDC point by inverse(projection * view), what must you do?
- Normalize it
- Divide x, y, z by w
- Multiply by the viewport
- Nothing
What is special about rays from an orthographic camera?
- They all start at the camera position
- They all share the same direction; only the origin changes
- They cannot hit anything
- They point backwards