Game Development Reference
In-Depth Information
Also notice that we change the camera's location by assigning to
camera.position.z
.
Three.js uses a
spatial coordinate system
in which, by default, the x-axis increases
from left to right, the z-axis increases from back to front, and the y-axis increases
upward. Most objects have a
position
and
scale
, both of which are represented by a
three-dimensional vector (specifically
THREE.Vector3
). They also have a
rotation
represented by a
THREE.Euler
instance, which is an abstraction that allows treating
rotation much like a vector. All objects are initialized at the position (0, 0, 0), also
called the
origin
. Rotation also starts at (0, 0, 0), and scale starts at (1, 1, 1). Vectors are
very versatile, but usually all you'll need to do with them is assign to the
x
,
y
, and
z
properties. For example, if we wanted to move the camera upward, we could increase
camera.position.y
.
Finally, we can display the scene by asking the renderer to display it from the
camera's perspective:
renderer.render(scene, camera);
Hooray, a static 3D display! If you have been following along by rebuilding our
scene from scratch, now is the point at which you can actually see the results of your
work. Just open the HTML file in a browser. (If you're loading the
three.js
file from
GitHub instead of locally, you'll need to be connected to the Internet.)
A static scene isn't very fun though, so let's add animation by constructing a
render loop:
animate();
function animate() {
requestAnimationFrame(animate);
mesh.rotation.x = Date.now() * 0.00005;
mesh.rotation.y = Date.now() * 0.0001;
renderer.render(scene, camera);
}
The key here is
requestAnimationFrame()
, which executes the function passed to
it when the browser is ready to paint a new frame. In that function, we perform any
necessary updates to the scene (in this case, changing the mesh's
rotation
vector
just like we changed the camera's
position
vector earlier) and then ask the renderer
to repaint the canvas as before.