One basic way to interact with models in a scene is to click on them with the mouse. In order to determine which model has been clicked on, a ray is shot into the scene from the clicked location, and the models intersected by the ray are determined. Shooting rays is also important to provide other functionality like determining what is hit by a bullet or clamping an object to the terrain directly below it. This example allows you to click one of two vehicles and then drive the selected vehicle using the WASD keys.
In order to determine intersection of a specific set of models with a ray, we need to keep a list of the eligible models. This list is called colliders
, and the mesh of each model is added to it via a line like the following.
colliders.push( mesh );
When the mouse is clicked, we first determine the X and Y coordinates of the click. The coordinates are then scaled in the range of [-1,+1] (why?). Adding in an arbitrary positive Z component, we have a vector originating at the mouse click and pointing directly into the screen. This vector is in the camera's coordinate frame.
projector.unprojectVector( vector, camera );
The vector is then converted to world coordinates using a projector
. A ray originating from the camera pointing in the specified direction is constructed. The ray is then intersected with the set of colliders, and collisions
list holds the results.
var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
var collisions = ray.intersectObjects( colliders );
The collisions
list contains information that can provide access to the selected model.
selectedObject = collisions[0].object;