3D Game Programming

(C. Jardin) #1
JavaScript doesn’t have to come from other locations. For most of this book,
we’re coding inside an HTML web page.

9.3 Setting the Scene


To do anything in 3D programming, we need a scene. Think of the scene as
the universe in which all of the action is going to take place. For something
so important, it’s really easy to create. The following code in ICE does just
that:

// This is where stuff in our game will happen:
varscene =newTHREE.Scene();

Scenes are really simple to work with. We’ve been adding objects to them
throughout the book. Once things have been added to a scene, it’s the scene’s
job to keep track of everything. In fact, that’s pretty much all we need to know
about scenes—after creating one, we add lots of stuff to it and the scene takes
care of the rest.

9.4 Using Cameras to Capture the Scene


Scenes do a great job of keeping track of everything, but they don’t show us
what’s happening. To see anything in the scene, we need a camera. Notice
the following code in ICE:

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

The purpose of the aspect_ratio is to determine the shape of the browser. This
is the same thing as aspect ratios for movie screens and TV sets. A large TV
with a 4:3 aspect ratio might be four meters wide and three meters tall (OK
that’s a really large TV). An even larger 4:3 screen might be twelve meters
wide and nine meters tall (multiply both the 4 and 3 in 4:3 by 3 to get 12:9).
Most movies today are made at an aspect ratio of 16:9, which would mean a
nine-meter-tall screen would be sixteen meters wide—four extra meters when
compared with the same-height 4:3 aspect ratio.

Why does this matter for us? If you try to project a movie made in 16:9 onto
a 4:3 screen, a lot of squishing has to be done. Similarly, a 4:3 movie would
need to be stretched to be shown on a 16:9 screen. Instead of stretching or
squishing, most movies are chopped so that you miss those four meters of
action. Our Three.js library doesn’t chop—it stretches or squishes. In other
words, it’s pretty important to get the aspect ratio right.

report erratum • discuss

Setting the Scene • 87


Prepared exclusively for Michael Powell

Free download pdf