Game Development Reference
In-Depth Information
Clicking
Clicking on the screen in order to select or interact with something is a common
requirement, but it's somewhat harder than it sounds because of the need to project
the location of the click in the 2D plane of your screen into the 3D world of Three.js. To
do this, we draw an imaginary line, called a ray, from the camera toward the position
where the mouse might be in 3D space and see if it intersects with anything.
In order to project, we first need a projector:
projector = new THREE.Projector();
Then we need to register a listener on the click event for the canvas:
renderer.domElement.addEventListener('mousedown', function(event) {
var 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
);
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(
camera.position,
vector.sub(camera.position).normalize()
);
var intersects = raycaster.intersectObjects(OBJECTS);
if (intersects.length) {
// intersects[0] describes the clicked object
}
}, false);
The previous code assumes that you are using the PerspectiveCamera
class. If you are using the OrthographicCamera class, projectors have a
utility method that returns an appropriate raycaster, and you do not have
to un-project the vector first:
var raycaster = projector.pickingRay(vector, camera);
 
Search WWH ::




Custom Search