3D Game Programming

(C. Jardin) #1

Adding Sunlight


Our raft is going to be making jumps and bumping into things. This will be
more fun if there are shadows. For shadows, we need light. Let’s start our
code outline just below the START CODING line with an addSunlight() call:

addSunlight(scene);

Adding sunlight to a game is something of an art. Now that you’re a program-
mer, I’ll let you in on a secret: when programmers say that something is more
art than science, we really mean we’re just guessing. In other words, we try
some numbers and play with them until we think they look right. The following
should end up looking right for us (but feel free to play with the numbers
yourself!):

functionaddSunlight(scene) {
varsunlight =newTHREE.DirectionalLight();
sunlight.intensity = 0.5;
sunlight.castShadow = true;
sunlight.position.set(250, 250, 250);
sunlight.shadowCameraNear = 250;
sunlight.shadowCameraFar = 600;
sunlight.shadowCameraLeft = -200;
sunlight.shadowCameraRight = 200;
sunlight.shadowCameraTop = 200;
sunlight.shadowCameraBottom = -200;
sunlight.shadowMapWidth = 4096;
sunlight.shadowMapHeight = 4096;

scene.add(sunlight);
}

That looks like a lot of code for what might seem like simple light. Most of it
has to do with the art of 3D programming. In fact, only the first two lines are
really needed. They tell the light to be not too bright (intensity = 0.5) and to cast
shadows (castShadows = true).

So what are the rest of the lines for? Well, the remaining numbers help make
nice-looking shadows without forcing the computer to work too hard. You
can skip to the next section if you don’t need the details.

Adding a directional light to a scene is like adding the sun to the sky. The
position that we give a directional light in a scene describes the location of
the sun in the sky. Here it’s 250 to the right, 250 to the front, and 250 above
the center of the scene. So, when this directional light shines down, shadows
will be to the left, toward the back, and fall on the ground.

report erratum • discuss

Organizing Code • 187


Prepared exclusively for Michael Powell

Free download pdf