Graphics Reference
In-Depth Information
This is a standard
THREE.PerspectiveCamera
object, which we also use
in most of the other examples in this chapter. Once again, no special config-
uration is required.
3. For the final step, we define the render loop that will render the scene and
also point the camera in the right direction for this recipe:
function render() {
var sphere =
scene.getObjectByName('sphere');
renderer.render(scene, camera);
camera.lookAt(sphere.position);
step += 0.02;
sphere.position.x = 0 + (10 *
(Math.cos(step)));
sphere.position.y = 0.75 * Math.PI /
2 + (6 * Math.abs(Math.sin(step)));
requestAnimationFrame(render);
}
In the
render
function, we use the
camera.lookAt
function to point the camera to
the
position
function of the sphere. As we do this in every frame that we render, it
will look like camera is exactly following the position of sphere.
How it works...
THREE.PerspectiveCamera
extends from the
THREE.Object3D
object.
THREE.Object3D
provides the
lookAt
function. When this function is called with
the target position to look at, Three.js creates a transformation matrix
(
THREE.Matrix4
) that aligns the position of the
THREE.Object3D
object with the
target's position. In the case of the camera, the result is that the target object is fol-
lowed around the scene by the camera and is rendered in the middle of the screen.
There's moreā¦
In this recipe, we use the
lookAt
function to point a camera to a specific object. You
can apply this same recipe for all the Three.js objects that extend from Object3D.