Ray–Sphere
Hitscan weapons, mouse picking against characters, line-of-sight checks and every ray tracer start with the ray–sphere test. It is short, exact, and a perfect example of turning geometry into a quadratic equation.
The math
A point p is on a sphere with center c and radius r when |p - c|² = r². Put the ray p = o + d t in, with oc = o - c:
(d · d) t² + 2 (oc · d) t + (oc · oc - r²) = 0With a unit direction d · d = 1, and using b = oc · d and c' = oc · oc - r², the solutions are:
discriminant = b² - c'
t = -b ± sqrt(discriminant)discriminant < 0: the ray misses the sphere.- The smaller
tis where the ray enters, the larger where it leaves. - If the entry
tis negative but the exit is positive, the ray started inside the sphere. - If both are negative, the sphere is behind the ray.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <optional>
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 normalize(Vec3 v) { return v * (1 / std::sqrt(dot(v, v))); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
// Returns the distance to the first hit in front of the origin (dir must be unit length).
std::optional<double> raySphere(Vec3 o, Vec3 d, Vec3 center, double r) {
Vec3 oc = o - center;
double b = dot(oc, d);
double c = dot(oc, oc) - r * r;
if (c > 0 && b > 0) return std::nullopt; // outside and pointing away: early out
double disc = b * b - c;
if (disc < 0) return std::nullopt; // misses
double t = -b - std::sqrt(disc); // entry point
if (t < 0) t = -b + std::sqrt(disc); // started inside: use the exit point
return t;
}
int main() {
std::cout << std::fixed << std::setprecision(3);
Vec3 enemy{0, 1, -10};
const double r = 1;
struct { const char* name; Vec3 o, d; } shots[] = {
{"dead center ", {0, 1, 0}, {0, 0, -1}},
{"grazing ", {0.9, 1, 0}, {0, 0, -1}},
{"miss ", {1.5, 1, 0}, {0, 0, -1}},
{"wrong way ", {0, 1, 0}, {0, 0, 1}},
{"from inside ", {0, 1, -10}, {1, 0, 0}},
{"diagonal ", {-6, 1, -4}, normalize({1, 0, -1})},
};
for (auto& s : shots) {
auto t = raySphere(s.o, s.d, enemy, r);
std::cout << s.name;
if (!t) { std::cout << "no hit\n"; continue; }
Vec3 p = s.o + s.d * *t;
Vec3 n = (p - enemy) * (1 / r); // surface normal at the hit
std::cout << "t=" << *t << " hit (" << z0(p.x) << ", " << z0(p.y) << ", " << z0(p.z) << ") normal ("
<< z0(n.x) << ", " << z0(n.y) << ", " << z0(n.z) << ")\n";
}
}dead center t=9.000 hit (0.000, 1.000, -9.000) normal (0.000, 0.000, 1.000)
grazing t=9.564 hit (0.900, 1.000, -9.564) normal (0.900, 0.000, 0.436)
miss no hit
wrong way no hit
from inside t=1.000 hit (1.000, 1.000, -10.000) normal (1.000, 0.000, 0.000)
diagonal t=7.485 hit (-0.707, 1.000, -9.293) normal (-0.707, 0.000, 0.707)
The normal at the hit point is simply (hit - center) / radius. That is what a game uses to spawn a blood or spark effect facing the right way, or to reflect a laser.
Picking the closest of many
A shot can pass through several spheres. Keep the smallest t:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <optional>
#include <string>
#include <vector>
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}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
std::optional<double> raySphere(Vec3 o, Vec3 d, Vec3 center, double r) {
Vec3 oc = o - center;
double b = dot(oc, d), c = dot(oc, oc) - r * r;
if (c > 0 && b > 0) return std::nullopt;
double disc = b * b - c;
if (disc < 0) return std::nullopt;
double t = -b - std::sqrt(disc);
return t < 0 ? -b + std::sqrt(disc) : t;
}
struct Target { std::string name; Vec3 c; double r; };
int main() {
std::cout << std::fixed << std::setprecision(2);
std::vector<Target> scene = {
{"barrel", {0.3, 0, -12}, 0.8},
{"crate", {-0.2, 0, -6}, 0.6},
{"guard", {0, 0, -20}, 1.0},
{"bird", {0, 5, -8}, 0.3},
};
Vec3 o{0, 0, 0}, d{0, 0, -1};
const Target* best = nullptr;
double bestT = 1e30;
for (const auto& t : scene) {
if (auto hit = raySphere(o, d, t.c, t.r); hit && *hit < bestT) { bestT = *hit; best = &t; }
}
if (best) std::cout << "first hit: " << best->name << " at distance " << bestT << "\n";
}first hit: crate at distance 5.43
Real engines don't loop over every object: a spatial structure (a grid, a BVH) returns only the few candidates near the ray. The per-object test is still exactly this.
Spheres as proxies
Hitscan games often test rays against spheres or capsules around body parts (head, torso, limbs) rather than against the render mesh, because it is fast and gives clean hit zones for damage multipliers. A capsule test is a ray-vs-sphere test against the closest point on the capsule's line segment (see Closest Point Queries).
Tip: The early-out line (
c > 0 && b > 0) skips the square root for most misses in a big scene: if the origin is outside the sphere and the ray points away from it, there can be no hit.
Test yourself
What does a negative discriminant mean in the ray–sphere test?
- The ray hits twice
- The ray misses the sphere
- The ray starts inside
- The sphere is behind the ray
The entry t is negative and the exit t is positive. What does it mean?
- A miss
- The ray starts inside the sphere
- The sphere is behind
- The ray is parallel
What is the surface normal at a hit point p on a sphere with center c and radius r?
- (c - p) / r
- (p - c) / r
- p / r
- The ray direction