Game Development Reference
In-Depth Information
The previous code listens to the mousedown event on the renderer's canvas. Then,
it creates a new Vector3 instance with the mouse's coordinates on the screen
relative to the center of the canvas as a percent of the canvas width. That vector
is then un-projected (from 2D into 3D space) relative to the camera.
Once we have the point in 3D space representing the mouse's location, we draw a
line to it using the Raycaster . The two arguments that it receives are the starting
point and the direction to the ending point. We determine the direction by
subtracting the mouse and camera positions and then normalizing the result, which
divides each dimension by the length of the vector to scale it so that no dimension
has a value greater than 1 . Finally, we use the ray to check which objects are located
in the given direction (that is, under the mouse) with the intersectObjects
method. OBJECTS is an array of objects (generally meshes) to check; be sure to change
it appropriately for your code. An array of objects that are behind the mouse are
returned and sorted by distance, so the first result is the object that was clicked.
Each object in the intersects array has an object , point , face , and distance
property. Respectively, the values of these properties are the clicked object (generally
a Mesh ), a Vector3 instance representing the clicked location in space, the Face3
instance at the clicked location, and the distance from the camera to the clicked point.
It's also possible to go in reverse (3D to 2D) by projecting instead of un-projecting:
var widthHalf = 0.5 * renderer.domElement.width / renderer.
devicePixelRatio,
heightHalf = 0.5 * renderer.domElement.height / renderer.
devicePixelRatio;
var vector = mesh.position.clone(); // or an arbitrary point
projector.projectVector(vector, camera);
vector.x = vector.x * widthHalf + widthHalf;
vector.y = -vector.y * heightHalf + heightHalf;
After this code runs, vector.x and vector.y will hold the horizontal and
vertical coordinates of the specified point relative to the upper-left corner of
the canvas. (Make sure you actually specify the point you want, instead of using
mesh.position.clone() , and that you've instantiated your projector .) Note that
the resulting coordinates might not be over the canvas if the original 3D point is not
on the screen.
 
Search WWH ::




Custom Search