3D Game Programming

(C. Jardin) #1
// This is what sees the stuff:
varaspect_ratio = window.innerWidth / window.innerHeight;
varcamera =newTHREE.PerspectiveCamera(75, aspect_ratio, 1, 1e6);
camera.position.z = 1000;
scene.add(camera);

One other change that we’ll make is to switch to the WebGLRenderer like we did
in Chapter 12, Working with Lights and Materials, on page 109.

// This will draw what the camera sees onto the screen:
varrenderer =newTHREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

If the WebGLRenderer Doesn’t Work on Your Computer
If the WebGLRenderer didn’t work for your computer when you tested
it in Chapter 12, Working with Lights and Materials, on page 109,
you can still do most of this chapter. You’ll need to keep the Canvas-
Renderer here. In the following code, replace the MeshPhongMaterial ref-
erences with MeshBasicMaterial. The simulation won’t look as cool—and
you won’t be able to do the last bit—but most of it will still work.

Now we start coding after START CODING ON THE NEXT LINE.


First, let’s do something important for a space simulation. Let’s make space
black.

document.body.style.backgroundColor ='black';

Now add the sun to our simulation.


varsurface =newTHREE.MeshPhongMaterial({ambient: 0xFFD700});
varstar =newTHREE.SphereGeometry(50, 28, 21);
varsun =newTHREE.Mesh(star, surface);
scene.add(sun);

varambient =newTHREE.AmbientLight(0xffffff);
scene.add(ambient);

varsunlight =newTHREE.PointLight(0xffffff, 5, 1000);
sun.add(sunlight);

The color of the sun is gold from http://en.wikipedia.org/wiki/List_of_colors (recall that
we replace the # on that page with 0x when making JavaScript colors). We
make this the ambient color because there won’t be other lights shining on
the sun. This is the color it gets just by being there.

For the ambient color to work, we need an ambient light, which we add. For
the sun to give light to the planets in our solar system, we need to add a point

A1.13Code: Build Your Own Solar System


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf