Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.1 — Raycasting and Picking
3D Web · Example 3 of 3

What a hit carries, and clicking an instance

Three tyres are one InstancedMesh: one draw call, and instanceId says which one. Click a tyre in the scene: the console prints "you clicked: tyre N".

A click gives two pixel numbers. A ray from the camera through that pixel finds the first object it touches. You convert the pixel with the canvas's own box, read the hit list, and meet the cases that surprise people: empty space, glass, hidden hit-boxes and a canvas that is not in the page's corner.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 4 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write ndcFromEvent(event, canvas) that returns a THREE.Vector2 in NDC from a pointer event, using the canvas's box.

02

Write firstPart(hits, names) that returns the first hit whose object, or any ancestor, has a name in names, or null.

Explain it without notes

01

A click at clientX = 400, clientY = 200 on a canvas whose box is left 100, top 50, width 600, height 300 happens in the middle of the canvas. What are the NDC values, and what would the innerWidth formula give on a 1000 × 800 window?

02

A customer clicks a part that has a transparent glass cover in front of it. What does intersectObjects return, and how do you pick the part anyway?

What a hit carries, and clicking an instance
Press Run to see the page.
idle

Console

Nothing logged yet.

Expected console output

object:     tyres
instanceId: 2
distance:   5.21 metres from the camera
point:      1.47, 0.52, 0.09
normal:     -0.03, 0.26, 0.97
faceIndex:  144
uv:         0.26, 0.21
middle tyre: 1