3D Game Programming

(C. Jardin) #1
After we build a new camera, we need to add it to the scene. Like anything
else in 3D programming, the camera is placed at the center of the scene to
which we add it. We move it 500 units away from the center in the Z direction
(“out” of the screen) so that we have a good view of what’s going on back at
the center of the scene.

9.5 Using a Renderer to Project What the Camera Sees


The scene and the camera are enough to describe how the scene looks and
from where we’re viewing it, but one more thing is required to show it on the
web page. This is the job of the renderer. It shows, or renders, the scene as
the camera sees it:

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

We have to tell the renderer the size of the screen to which it will be drawing.
We set the size of the view to take up the whole browser (window.innerWidth and
window.innerHeight).

To include the renderer in the web page, we use its domElement property. A
domElement is another name for an HTML tag like those we added earlier in the
chapter. Instead of holding a title or paragraph, this domElement holds our
amazing 3D worlds.

We add that domElement to the document.body—which is the same <body> tag that
held the HTML from earlier. The appendChild() function takes care of adding the
domElement to the document body. If you’re wondering why we have names like
appendChild() and domElement, all I can tell you is to be glad you are a 3D-game
programmer, not a web programmer. Web programmers have to use silly (and
hard-to-remember) names like this all the time.

At this point, the renderer can draw to the screen, but we still need to tell it
to render before anything will show up. This is where renderer.render() comes
into play at the end of your current code.

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

It might seem as though the renderer is an obnoxious younger brother or
sister, doing the right thing only when we’re extremely specific in our
instructions. In a sense this is true, but in another sense all programming is
like this. Until we tell the computer in exactly the right way to do something,
it often does something completely unexpected.

Chapter 9. What’s All That Other Code? • 88


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf