# 07. Hover and click with Raycaster, explained

**Goal:** find out which 3D object is under the mouse or finger, highlight it on hover, and toggle it on click without breaking orbit dragging.

## How picking works

1. Convert the pointer position from pixels to **normalized device coordinates (NDC)**: x and y from -1 to 1, with +y up.
2. `raycaster.setFromCamera(ndc, camera)` builds a ray from the camera through that point.
3. `raycaster.intersectObjects(list)` tests the ray against the objects and returns hits sorted by distance.

## Walkthrough

```js
ball.userData.selected = false;
```
`userData` is an empty object on every `Object3D` for your own data (ids, state, links to app data). It is also copied by `clone()` and serialized by `toJSON()`.

```js
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
```
Using the canvas rectangle (not `window.innerWidth`) keeps picking correct when the canvas is not full-screen or the page scrolls. The minus sign flips Y because screen pixels grow downward.

```js
const hits = raycaster.intersectObjects(pickables, false);
```
Testing only a list of pickable objects is faster and avoids hitting helpers, ground planes or invisible objects. The second argument `false` means "do not test children". Each hit has `object`, `distance`, `point` (world position), `face` and, for instanced meshes, `instanceId`.

```js
hovered.material.emissive.setHex(0x333333);
```
Changing `emissive` brightens the hovered sphere without touching its base color. Each sphere has **its own material**; if they shared one material, highlighting one would highlight all.

```js
if (Math.hypot(event.clientX - downAt.x, event.clientY - downAt.y) > 4) return;
```
OrbitControls also uses the pointer. Treat a pointerup as a click only when the pointer moved less than a few pixels since pointerdown; otherwise it was a drag to orbit.

## Performance tips

| Situation | Tip |
| --- | --- |
| Many objects | Keep a separate array of pickables; consider a BVH library such as three-mesh-bvh for large meshes |
| Raycasting on every `pointermove` | Fine for dozens of objects; throttle or raycast once per frame for thousands |
| Points and lines | Adjust `raycaster.params.Points.threshold` and `raycaster.params.Line.threshold` |
| Layers | `raycaster.layers.set(n)` tests only objects on that layer |

## Try this

1. Show the hit `point` by moving a small marker sphere to `hits[0].point`.
2. Add keyboard support: Tab through spheres with a hidden HTML list and mirror the focus in 3D (accessibility for 3D UIs).
3. Make pickables draggable with `DragControls` from `three/addons/controls/DragControls.js`.
