Raycaster
Quick answer
Raycaster casts a ray through the scene and returns hit records with object, distance, point, face, and uv, powering 3D picking. Set it from normalized device coordinates with setFromCamera(), then call intersectObject() or intersectObjects() and read the sorted results. Adjust params.Points.threshold and params.Line.threshold for thin or sparse geometry.
new THREE.Raycaster ( origin , direction , near , far ) → Raycaster
Key points
- setFromCamera(coords, camera) expects NDC coordinates with x and y between -1 and 1.
- intersectObjects(list, true) tests descendants and returns hits sorted by distance.
- instanceId identifies which instance of an InstancedMesh was hit.
Example
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const targets = []; // 只放需要参与拾取的对象
renderer.domElement.addEventListener('pointerdown', function (event) {
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;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(targets, false);
if (!hits.length) return;
console.log(hits[0].object.name, hits[0].point.toArray());
});const ground = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0); // y = 0
const hitPoint = new THREE.Vector3();
raycaster.setFromCamera(pointer, camera);
const ok = raycaster.ray.intersectPlane(ground, hitPoint);
if (ok) marker.position.copy(hitPoint);
Notes
- An unnormalized direction distorts distances and threshold tests; call normalize().
- Hit records carry no feature attributes; map them through object.userData yourself.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Raycaster. https://www.jingweizhi.com/en/three/api/raycaster.html (accessed 2026-11-03).