Pointer Raycasting
"What did the player click?" In 3D the answer is a ray: start at the camera, go through the point under the mouse, and find the first object it hits. THREE.Raycaster does exactly that, and the same tool answers other game questions: is there ground under my feet, can this guard see the player, where does this bullet hit, which tile is under the cursor?
From mouse to ray
The raycaster needs the pointer in normalized device coordinates (NDC): x and y from −1 to +1, with +y up. Convert from CSS pixels relative to the canvas:
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
canvas.addEventListener('pointermove', (e) => {
const r = canvas.getBoundingClientRect();
pointer.x = ((e.clientX - r.left) / r.width) * 2 - 1;
pointer.y = -((e.clientY - r.top) / r.height) * 2 + 1; // CSS y goes down, NDC y goes up
});
// later (in the loop or on click):
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(pickables, false); // false: don't descend into children
if (hits.length) console.log(hits[0].object.name, hits[0].point, hits[0].distance);Each hit has distance, point (world position), face (with its normal), object, uv, and for instanced meshes instanceId. Hits are sorted by distance, so hits[0] is the closest.
Under the hood: ray against sphere
Before testing triangles, Three.js checks each mesh's bounding sphere: if the ray misses the sphere it can't hit the mesh, and the triangles are skipped. That test is a few lines of maths (see Ray–Sphere in Math for Games):
// Ray: origin o, unit direction d. Sphere: centre c, radius r. Returns the distance or null.
function raySphere(o, d, c, r) {
const oc = [o[0] - c[0], o[1] - c[1], o[2] - c[2]];
const b = oc[0] * d[0] + oc[1] * d[1] + oc[2] * d[2];
const cc = oc[0] ** 2 + oc[1] ** 2 + oc[2] ** 2 - r * r;
const disc = b * b - cc;
if (disc < 0) return null; // the ray misses
const t = -b - Math.sqrt(disc); // nearest intersection
return t >= 0 ? t : null; // behind the origin doesn't count (simplified)
}
const eye = [0, 1.6, 5], forward = [0, 0, -1];
const things = [['barrel', [0, 1.2, -3], 0.6], ['crate', [2, 1, -2], 0.8], ['lamp', [0, 1.6, -10], 0.3]];
for (const [name, c, r] of things) {
const t = raySphere(eye, forward, c, r);
console.log(`${name.padEnd(6)} ${t === null ? 'miss' : `hit at distance ${t.toFixed(2)}`}`);
}barrel hit at distance 7.55
crate miss
lamp hit at distance 14.70
Both the barrel and the lamp are on the ray, and the closest hit wins, exactly like hits[0]. Because the bounding-sphere check is cheap and the triangle check is not, raycasting against a 100,000-triangle model the ray actually crosses is slow (every triangle is tested). For that, games ray-cast against simple stand-in shapes, or use three-mesh-bvh (see lil-gui, Spector.js & three-mesh-bvh).
Hover, click, move
The playground combines the three most common uses:
- Hover: the object under the pointer lights up (an emissive tint).
- Click an object to select it.
- Click the ground to send the selected unit there, point-and-click style. The ring marks the target.
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block; touch-action: none }
#hud { position: fixed; left: 10px; top: 8px; color: #fff; font: 13px system-ui, sans-serif; text-shadow: 0 1px 2px #000; pointer-events: none }</style>
<div id="hud">Click a unit to select it, then click the ground to move it.</div>
<script type="module">
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const canvas = renderer.domElement;
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1a2131');
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 7, 7.5);
camera.lookAt(0, 0, 0);
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
scene.add(new THREE.HemisphereLight('#fff', '#334', 1.4));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(3, 8, 4);
scene.add(sun);
const ground = new THREE.Mesh(new THREE.PlaneGeometry(16, 16), new THREE.MeshStandardMaterial({ color: '#3c5a40' }));
ground.rotation.x = -Math.PI / 2;
ground.name = 'ground';
scene.add(ground, new THREE.GridHelper(16, 16, '#567', '#4a6650'));
const units = ['#ef5350', '#42a5f5', '#ffca28'].map((color, i) => {
const u = new THREE.Mesh(new THREE.CylinderGeometry(0.4, 0.4, 1, 20), new THREE.MeshStandardMaterial({ color }));
u.position.set((i - 1) * 2.5, 0.5, 0);
u.name = ['Red', 'Blue', 'Yellow'][i];
u.userData.target = u.position.clone();
scene.add(u);
return u;
});
const ring = new THREE.Mesh(new THREE.RingGeometry(0.45, 0.6, 32), new THREE.MeshBasicMaterial({ color: '#ffffff' }));
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.02;
ring.visible = false;
scene.add(ring);
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2(10, 10); // off-screen until the pointer moves
let hovered = null, selected = null;
function setPointer(e) {
const r = canvas.getBoundingClientRect();
pointer.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
}
canvas.addEventListener('pointermove', setPointer);
canvas.addEventListener('pointerleave', () => pointer.set(10, 10));
canvas.addEventListener('pointerdown', (e) => {
setPointer(e);
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects([...units, ground], false)[0];
if (!hit) return;
if (hit.object !== ground) {
selected = hit.object;
console.log(`selected ${selected.name}`);
} else if (selected) {
selected.userData.target.set(hit.point.x, 0.5, hit.point.z);
ring.position.set(hit.point.x, 0.02, hit.point.z);
ring.visible = true;
}
});
const timer = new THREE.Timer();
renderer.setAnimationLoop((t) => {
timer.update(t);
const dt = Math.min(Math.max(timer.getDelta(), 0), 0.1);
// Hover test once per frame, not on every pointermove event.
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(units, false)[0];
hovered = hit ? hit.object : null;
for (const u of units) {
u.material.emissive.set(u === hovered ? '#444444' : u === selected ? '#222222' : '#000000');
const to = u.userData.target.clone().sub(u.position);
const step = Math.min(to.length(), 4 * dt); // 4 units per second
if (step > 1e-4) u.position.addScaledVector(to.normalize(), step);
}
canvas.style.cursor = hovered ? 'pointer' : 'default';
renderer.render(scene, camera);
});
</script>Two habits from this code are worth keeping:
- Raycast once per frame for hover, using the last known pointer position, instead of in every
pointermovehandler (mice can fire hundreds of events per second). - Pass an explicit list of pickable objects to
intersectObjects, notscene.childrenwithrecursive = true. It's faster and avoids hitting helpers, particles or the player's own body.
Rays that aren't from the mouse
raycaster.set(origin, direction) takes any ray (direction must be normalized). Set near and far to limit its length:
// Ground check: is there floor within 1.1 m below the character's centre?
down.set(0, -1, 0);
raycaster.set(player.position, down);
raycaster.far = 1.1;
const onGround = raycaster.intersectObjects(level.colliders, false).length > 0;
// Line of sight: can the guard see the player? (anything closer than the player blocks it)
dir.subVectors(player.position, guard.position);
const dist = dir.length();
raycaster.set(guard.position, dir.normalize());
raycaster.far = dist;
const blocked = raycaster.intersectObjects(level.walls, false).length > 0;For movement and collisions in a real game, prefer the physics engine's ray and shape casts (Rapier's castRay, cannon-es's raycastClosest): they test simplified collision shapes and are much faster than triangle raycasts against render meshes.
Layers and filtering
raycaster.layers works like a camera's layers: only objects on an enabled layer are tested. Put pickable objects on their own layer (obj.layers.enable(2); raycaster.layers.set(2)) to skip everything else. Points and lines have their own thresholds: raycaster.params.Points.threshold and raycaster.params.Line.threshold (in world units).
Tip: Invisible objects are still hit by raycasts (
visibledoesn't matter to the raycaster). That's handy for invisible trigger volumes and large invisible "click planes", and a classic surprise when a hidden object keeps blocking clicks.
Test yourself
The pointer is in the top-left corner of the canvas. What are its NDC coordinates?
- (0, 0)
- (−1, +1)
- (+1, −1)
- (−1, −1)
Which hit in raycaster.intersectObjects(list) is the closest object?
- The last element
hits[0]: results are sorted by distance- It depends on the order of
list - The one with the largest
distance
A mesh with visible = false keeps blocking your clicks. Why?
- It is a rendering bug
- Raycasting ignores
visible; filter it out of the list or use layers - The bounding sphere is stale
- Raycaster.far is too large