Capítulo 837 de 859
Two common ways to figure out which object a user clicked: CPU-side raycasting (simple, but can't see through per-pixel texture transparency) and GPU-based picking (draws each object with a unique id color offscreen and reads back one pixel — handles transparency correctly at the cost of drawing every object twice).
Raycaster): casts a ray from the camera through the mouse position and tests it against scene geometry; bounding-sphere/box checks first avoid testing every triangle of every object.PerspectiveCamera.setViewOffset: lets you render only the tiny sub-rectangle of the frame corresponding to the cursor, so the offscreen id-pass can be limited to effectively one pixel instead of a full-resolution render.MeshPhongMaterial by setting emissive to the id color and color/specular to black with blending: NoBlending, so the rendered pixel is exactly the id color where the texture's alpha passes alphaTest — a custom shader would be the more correct, cheaper solution.class PickHelper {
constructor() {
this.raycaster = new THREE.Raycaster();
this.pickedObject = null;
}
pick(normalizedPosition, scene, camera) {
this.raycaster.setFromCamera(normalizedPosition, camera);
const intersectedObjects = this.raycaster.intersectObjects(scene.children);
if (intersectedObjects.length) {
this.pickedObject = intersectedObjects[0].object;
this.pickedObject.material.emissive.setHex(0xffff00);
}
}
}
Raycaster) is the simplest picking approach but can't distinguish a transparent texture pixel from an opaque one.setViewOffset on the camera can restrict that second pass to roughly the one pixel under the cursor, limiting the extra cost.MeshPhongMaterial's lighting-affected properties.setViewOffset, used to limit the GPU-picking render.