3D Game Programming

(C. Jardin) #1
Next we need to make the moon behave a bit more like a moon. Instead of
orbiting around the sun, we need to make it orbit around Earth. So delete
the lines that set the moon’s position, and add it to the scene. Since the moon
is no longer added to the scene, it will disappear—this is OK. We’ll add it back
in a second.

But first, let’s remove the code that moves the moon around. Inside the curly
braces of the animate() function, delete the lines that calculate y_diff, x_diff, and
angle. Also delete the two lines that set the earth_cam rotation and position.

Finally, remove the line that sets the moon’s position with the sine and cosines,
the line just under var m_angle. We still need to do that for Earth, but we’ll try
something new to move the moon around.

Now that we have removed everything that made the moon behave like Mars,
we’re ready to make it do what the moon should—mainly, revolve around
Earth. To accomplish this, we’ll do something really sneaky.

14.3 The Coolest Trick: Frame of Reference


Just after we create the moon, we create the moon’s orbit, which is just an
empty 3D object—similar to what we did back in Chapter 3, Project: Making
an Avatar, on page 25. Then we add the orbit to Earth:

varmoon_orbit =newTHREE.Object3D();
earth.add(moon_orbit);

Adding the moon_orbit to Earth like that means that it’s centered on Earth.
And, no matter where Earth goes, this moon_orbit object stays with Earth.

It probably doesn’t seem like it, but this is a crazily important trick in 3D
programming. So important, in fact, that it gets a fancy name: frame of refer-
ence. Our moon_orbit is a new frame of reference. To see the power of frame-of-
reference thinking, we add the moon to the moon_orbit and move it 100 units
away from the center:

moon_orbit.add(moon);
moon.position.set(0, 100, 0);

With that, we should again see the moon, only now it’s stuck next to Earth
as Earth travels around the sun.

Since the moon_orbit frame of reference is always centered on Earth, the moon
is now always 100 units away from Earth. We still need to make the moon
revolve around Earth. We add Earth’s camera to the moon_orbit frame of refer-
ence and rotate it to face the moon:

report erratum • discuss

The Coolest Trick: Frame of Reference • 127


Prepared exclusively for Michael Powell

Free download pdf