3D Game Programming

(C. Jardin) #1
light in the middle of the sun. A point light shines light in all directions from
a single point, much like the sun.

With that, let’s create our planets and place them a little away from the sun
(obviously not to scale!).

varsurface =newTHREE.MeshPhongMaterial({ambient: 0x1a1a1a, color: 0x0000cd});
varplanet =newTHREE.SphereGeometry(20, 20, 15);
varearth =newTHREE.Mesh(planet, surface);
earth.position.set(250, 0, 0);
scene.add(earth);

varsurface =newTHREE.MeshPhongMaterial({ambient: 0x1a1a1a, color: 0xb22222});
varplanet =newTHREE.SphereGeometry(20, 20, 15);
varmars =newTHREE.Mesh(planet, surface);
mars.position.set(500, 0, 0);
scene.add(mars);

That should give us our sun, Earth, and Mars. So far, they are not doing
anything. Let’s fix that by changing the last line of code from a single render
to an animate() function.

clock =newTHREE.Clock();

functionanimate() {
requestAnimationFrame(animate);

vartime = clock.getElapsedTime();

vare_angle = time * 0.8;
earth.position.set(250* Math.cos(e_angle), 250* Math.sin(e_angle), 0);

varm_angle = time * 0.3;
mars.position.set(500* Math.cos(m_angle), 500* Math.sin(m_angle), 0);

// Now, show what the camera sees on the screen:
renderer.render(scene, camera);
}

animate();

We’ve already used the 3D clock timer, back in Chapter 6, Project: Moving
Hands and Feet, on page 59, when we wanted to move our avatar’s hands
and feet back and forth. To make the hands and feet move back and forth,
we didn’t use JavaScript—we used math. Specifically, we used sine. For our
planets, we are again using sine, but we are also using a new function, cosine.

If we just used a sine, our planets would move back and forth through the
sun, just like our avatar hands and feet moved back and forth. But we want

report erratum • discuss

The Sun, Earth, and Mars • 119


Prepared exclusively for Michael Powell

Free download pdf