Lesson 11 of 13

Raycasting

Raycasting

Raycasting lets you detect which 3D objects the mouse is hovering over or clicking on. A ray is cast from the camera through the mouse position into the scene.

Setting Up

const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();

window.addEventListener('mousemove', (e) => {
  // Normalize to [-1, +1] range
  pointer.x =  (e.clientX / innerWidth)  * 2 - 1;
  pointer.y = -(e.clientY / innerHeight) * 2 + 1; // Y is flipped
});

Casting the Ray

In the render loop, update the raycaster and check for intersections:

raycaster.setFromCamera(pointer, camera);
const intersects = raycaster.intersectObjects(scene.children);

if (intersects.length > 0) {
  const hit = intersects[0]; // closest object
  hit.object.material.color.set(0xff0000); // highlight
}

Intersection Data

Each intersection contains:

  • object — the intersected mesh
  • distance — distance from camera
  • point — world-space hit point (Vector3)
  • face — the hit face

Recursive

Pass true as second arg to check inside groups:

raycaster.intersectObjects(scene.children, true);

Your Task

Implement normalizePointer(clientX, clientY, width, height) that returns a THREE.Vector2 with properly normalized coordinates for raycasting.

Three.js loading...
Loading...
Click "Run" to execute your code.