3D Game Programming

(C. Jardin) #1
// This will draw what the camera sees onto the screen:
varrenderer =newTHREE.WebGLRenderer();
renderer.shadowMapEnabled = true;

It might seem like that’s enough—we told the renderer that it should draw
shadows, and it should take care of everything else. But shadows require a
lot of work by the computer. If every light makes shadows and every object
casts a shadow and every object can have a shadow fall on it...well, then the
computer is going to use all of its power drawing shadows and have nothing
left for the user to actually play games.

The next step is to mark the donut as making shadows. To do this, we set
the castShadow attribute after adding the donut to the scene. Add the
donut.castShadow line after scene.add(donut):

varshape =newTHREE.TorusGeometry(100, 50, 8, 20);
varcover =newTHREE.MeshPhongMaterial();
cover.emissive.setRGB(0.8, 0.1, 0.1);
cover.specular.setRGB(0.9, 0.9, 0.9);
vardonut =newTHREE.Mesh(shape, cover);
scene.add(donut);
donut.castShadow = true;

Now tell the sunlight that it makes shadows by setting castShadow on it, as
well. Again, add the sunlight.castShadow line after scene.add(sunlight):

varsunlight =newTHREE.DirectionalLight();
sunlight.intensity = 0.5;
sunlight.position.set(100, 100, 100);
scene.add(sunlight);
sunlight.castShadow = true;

Last, we need a place for the shadow to fall. In real life, we see a shadow on
a building or the ground. Let’s create some ground below the donut for the
shadow to fall on:

varshape =newTHREE.PlaneGeometry(1000, 1000);
varcover =newTHREE.MeshBasicMaterial();
varground =newTHREE.Mesh(shape, cover);
scene.add(ground);
ground.position.set(0, -200, 0);
ground.rotation.set(-Math.PI/2, 0, 0);
ground.receiveShadow = true;

Notice that we’re using a plane and a basic material for this. Always use the
simplest object you can.

With this, you should see that our awesome donut is casting a shadow:


Chapter 12. Working with Lights and Materials • 114


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf