Picking via ray casting

Shooting an invisible ray from the cursor into the scene to find out which 3D object was clicked or hovered.

raycastinghow do I click on a 3D objecthit detection from the mouseraycasingobject pickingclick detection in 3Dhover state on a meshmake the 3D model clickable

See it

Live demo coming soon

What it is

A canvas has no DOM elements inside it, so there is nothing to attach a click handler to. Picking rebuilds that: convert the pointer position into normalized device coordinates (x and y from -1 to 1), unproject that through the camera into a ray, and intersect the ray with scene geometry. three.js does it with Raycaster: setFromCamera(pointer, camera) then intersectObjects(scene.children, true), which hands back hits sorted nearest first, each with the object, the distance, the exact point, the face, and the UV.

That is how you get clickable hotspots, drag-to-move, hover highlights, and 'place the object where I clicked the floor'. In react-three-fiber it is already wired up: onClick and onPointerOver on a mesh are raycasts under the hood.

Gotchas worth knowing up front. Raycasting runs on the CPU against triangles, so doing it every mousemove over a dense scene is a real cost: throttle it, restrict the list of candidate objects, or use Layers. Instanced meshes report an instanceId rather than a separate object. Vertex-shader-deformed geometry is not picked where you see it, because the CPU only knows the original vertex positions. And skinned meshes and thin objects often want an invisible simplified proxy mesh as the hit target instead.

Ask AI for it

Make the meshes in this three.js scene clickable using a Raycaster. On pointer events, convert clientX/clientY into normalized device coordinates from the canvas bounding rect, call raycaster.setFromCamera(pointer, camera), then intersectObjects against an explicit array of pickable meshes (not the whole scene). Use the first hit to set a hover highlight and fire a click handler, read intersection.point for placement, and handle instanceId for InstancedMesh hits. Throttle the hover raycast to once per frame and set the cursor to pointer when something is hit.

You might have meant

bounding box bounding sphereorbit controlsmesh geometryscene graphdepth buffer z buffer