const handleMouseClick = (event) => {
event.preventDefault();
const vector = new THREE.Vector3(
renderer.devicePixelRatio * (event.pageX - this.offsetLeft) / this.width * 2 - 1,
-renderer.devicePixelRatio * (event.pageY - this.offsetTop) / this.height * 2 + 1,
0.5
);
projector.unprojectVector(vector, camera);
const raycaster = new THREE.Raycaster(
camera.position,
vector.sub(camera.position).normalize()
);
const intersects = raycaster.intersectObjects(YOUR_CLICKABLE_OBJECTS);
if (intersects.length > 0) {
camera.position.copy(intersects[0].point);
// Alternatively: camera.position.copy(intersects[0].object.position.clone());
}
};
renderer.domElement.addEventListener('mousedown', handleMouseClick, false);
This script:
- Attaches an event listener to detect mouse clicks
- Translates the 2D click location into a corresponding 3D position in the scene
- Projects a virtual line (ray) from the camera towards the clicked spot
- Determines if any objects intersect with the ray and moves the camera to the first intersection point
If you prefer a gradual transition of the camera to the clicked location instead of an abrupt jump, consider utilizing a tweening library such as TweenJS for precise control over the animation timing.
(P.S.: The use of renderer.devicePixelRatio
might only be necessary for WebGL renderers; feel free to omit it for other renderers.)