3D Game Programming

(C. Jardin) #1
In this game we need ground, an avatar, and a scoreboard. We’ll split the
action into two parts: animation and game logic. All of that is listed in our
code outline. Let’s get started writing the code that matches this outline.

Adding Ground for the Game


The first function call in our code outline is to the addGround() function. Just
below the code outline (after the commented-out //gameStep() line), define that
function as follows:

functionaddGround() {
document.body.style.backgroundColor ='#87CEEB';
ground =newPhysijs.PlaneMesh(
newTHREE.PlaneGeometry(1e6, 1e6),
newTHREE.MeshBasicMaterial({color: 0x7CFC00})
);
ground.rotation.x = -Math.PI/2;
scene.add(ground);
returnground;
}

The Physijs library “wraps” our 3D objects in code that makes collision
detection easier. That is why the ground is a Physijs.PlaneMesh instead of our
usual THREE.Mesh.

The collision detection that we did back in Chapter 10, Project: Collisions, on
page 93, is good for only simple collisions. In this game we need to detect
collisions with the ground and fruit. Multiple collisions are much harder, so
we’ll use the Physijs library to make our jobs easier.

Aside from the Physijs.PlaneMesh, everything in this function is familiar. We make
a large, green plane, rotate it flat, and add it to the scene.

Once this function is defined, we uncomment the call to addGround() in our
code outline. If everything is working, we should see green ground with blue
sky in the background.

Build a Simple Avatar


Making the avatar is similar. We use a Physijs Box to wrap a purple cube. We
do two other things to our avatar: start it moving and add event listeners for
collisions.

functionaddAvatar() {
avatar =newPhysijs.BoxMesh(
newTHREE.CubeGeometry(40, 50, 1),
newTHREE.MeshBasicMaterial({color: 0x800080})
);

Chapter 15. Project: The Purple Fruit Monster Game • 136


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf