3D Game Programming

(C. Jardin) #1
Next we need to add earth_cam to Earth and rotate it so that it points to Mars.
We do that inside the animate() function. Add the following after the line that
sets Mars’s position and before the renderer.render line.

vary_diff = mars.position.y - earth.position.y,
x_diff = mars.position.x - earth.position.x,
angle = Math.atan2(x_diff, y_diff);

earth_cam.rotation.set(Math.PI/2, -angle, 0);
earth_cam.position.set(earth.position.x, earth.position.y, 22);

If you know the difference between the X and Y coordinates of two objects,
you can again use math to figure out the rotation between the two things.
This is what we’re doing with the x_diff and y_diff variables—we are calculating
how far apart Mars’s and Earth’s X and Y positions are. This is what the
Math.atan2() tells us.

Declaring a Bunch of Variables with One var
You may have noticed that we used only one var keyword to build
the list of variables in the preceding code. JavaScript programmers
often find this a nice way to group a bunch of variables that are
related—in this case, two points and the angle between them. It’s
especially common to do this at the start of functions.

Once we know the rotation, we can place the camera at the same position as
Earth and then rotate it so it’s facing Mars.

Last, we need to add the ability to use the keyboard to switch between our
two cameras. Let’s use A to switch to the above_cam and E to switch to earth_cam.
The computer code for A is 65 and the computer code for E is 69. So, at the
very bottom of our code, before the ending <script> tag, add the following event
listener.

document.addEventListener("keydown",function(event) {
varcode = event.keyCode;

if(code == 65) {// A
camera = above_cam;
}
if(code == 69) {// E
camera = earth_cam;
}
});

That should do it! Now if you hide the code, you should be able to switch back
and forth between “Earth-cam” and “above-solar-system-cam.” Watching from

Chapter 13. Project: Build Your Own Solar System • 122


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf