3D Game Programming

(C. Jardin) #1
functionanimate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);

if(pause)return;
time = time + speed;
vare_angle = time * 0.001;
earth.position.set(250* Math.cos(e_angle), 250* Math.sin(e_angle), 0);
varm_angle = time * 0.02;
moon_orbit.rotation.set(0, 0, m_angle);
}
animate();

There are other changes in there, as well:



  • The renderer.render() line is no longer at the bottom. It is now the second
    line in animate().

  • We added a return statement if pause is true.

  • We increased the time by adding speed to it each time.

  • The number by which time is multiplied to calculate e_angle and m_angle has
    gotten smaller.


Once you have all of those changes made, the simulation should run again,
the same as before. We made those changes so that we could use key presses
to change some of the settings.

To do that, find the keydown listener and change it to the following:


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

if(code == 67) changeCamera();// C
if(code == 32) changeCamera();// space
if(code == 80) pause = !pause;// P
if(code == 49) speed = 1;// 1
if(code == 50) speed = 2;// 2
if(code == 51) speed = 10;// 3
});

functionchangeCamera() {
if(camera == above_cam) camera = earth_cam;
elsecamera = above_cam;
}

Now if you hide the code, you can change the camera by pressing either the
C key or the space bar. You can pause or unpause by pressing the P key. You
can even change the speed by pressing 1 , 2 , or 3.

Give it a try!


Chapter 14. Project: Phases of the Moon • 130


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf