3D Game Programming

(C. Jardin) #1
do all of the repetitive work of building the trunk and treetop in the function
named makeTreeAt(). We could have named it anything, but we give it a name
that tells us what it does—in this case, it makes a tree at the coordinates that
we defined.

We should be familiar with most of the things going on inside this function.


functionmakeTreeAt(x, z) {
❶ vartrunk =newTHREE.Mesh(
newTHREE.CylinderGeometry(50, 50, 200),
newTHREE.MeshBasicMaterial({color: 0xA0522D})
);

❷ vartop =newTHREE.Mesh(
newTHREE.SphereGeometry(150),
newTHREE.MeshBasicMaterial({color: 0x228B22})
);
❸ top.position.y = 175;
❹ trunk.add(top);

❺ trunk.position.set(x, -75, z);
❻ scene.add(trunk);
}

❶Make a trunk out of a cylinder.


❷Make a treetop out of a sphere.


❸Move the treetop up (remember Y is up and down) to the top of the trunk.


❹Add the treetop to the trunk.


❺Set the position of the trunk to the x and z that the function was called
with—makeTreeAt(500,0)). The Y value of -75 moves the trunk down enough
to look like a tree trunk.

❻Add the trunk to the scene.


It’s important to remember that we have to add the treetop to the trunk and
not the scene. If we added the treetop to the scene, then when we try to move
the tree, only the trunk will be moved and not the treetop. We would also
have to set the treetop position if we added it to the scene—adding it to the
trunk means that the treetop’s position is the same as the trunk’s.

By now we’re getting good at building objects from shapes and materials and
placing them on the screen. You could probably make four trees without too
much effort. For one tree you need a THREE.CylinderGeometry for the trunk and a
THREE.SphereGeometry for the top of the tree. If you add the green leaves to the
top of the tree, then you move both parts together.

Chapter 4. Project: Moving Avatars • 42


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf