3D Game Programming

(C. Jardin) #1
Another way to handle moving between levels is to remove and create specific
game elements—like platforms and obstacles—while the rest of the scene
stays the same. As games get more complicated, this becomes a very hard
way to do it. But in this game we only have a few obstacles, so this approach
will work just fine.

Let’s build a Levels object to hold this information. This is a slightly different
reason to use objects than we saw in the previous chapter. There we used a
Ramp object to help us easily create multiple ramps. This time we build a Levels
object because it will be easier to think of it as a single thing.

Add the Levels code below the scoreboard code, but before the animate() function.
Create the Levels function constructor as follows so that it sets four properties:

functionLevels(scoreboard, scene) {
this.scoreboard = scoreboard;
this.scene = scene;
this.levels = [];
this.current_level = 0;
}

The Levels object will need to know about each of these things to do what it
needs to do. It needs access to the scoreboard to reset the counter between
levels. It needs access to the scene to draw and remove obstacles. It needs to
have a list of things on the different levels. Finally, it needs to know what the
current level is.

Objects Should Work on Only Their Own Properties
We don’t really need to pass the scoreboard and scene objects into our
constructor. Since all of our code is in the same place, it’s possible
for our Levels object to do something directly to the scoreboard variable.

Never do that.


There are two reasons. First, if we split all of this code into separate
JavaScript libraries, then scoreboard and scene won’t always be defined
in the library. Second, your code will be cleaner. Object-oriented
programming is not easy. Use whatever rules you can to keep it
from getting messy. This is a good rule.

With the constructor out of the way, let’s define the methods for the Levels
object. First, we need a way to add a new level:

Levels.prototype.addLevel =function(things_on_this_level) {
this.levels.push(things_on_this_level);
};

report erratum • discuss

Building Levels • 179


Prepared exclusively for Michael Powell

Free download pdf