Cursor & Raycasting

Lesson 8

Raycasting shoots a ray from the camera through the cursor into the 3D scene — how Three.js determines what the mouse hovers over or clicks on.

Raycaster Setup

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

window.addEventListener('mousemove', (e) => {
  mouse.x = (e.clientX / innerWidth) * 2 - 1;
  mouse.y = -(e.clientY / innerHeight) * 2 + 1;
});

Hit Testing in the Loop

raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObjects(meshes);

if (hits.length > 0) {
  hits[0].object.material.emissive.set(0x333333);
} else {
  meshes.forEach(m => m.material.emissive.set(0x000000));
}

Mouse Parallax Depth

gsap.to(scene.rotation, {
  y: mouse.x * 0.1,
  x: -mouse.y * 0.05,
  duration: 1,
  ease: 'power2.out',
});

What to Experiment With

  • On click, fire a GSAP scale animation on the hit object
  • Use raycasting with a PlaneGeometry floor for world-space mouse position
  • Move a 3D cursor sphere to follow the nearest surface hit