3D Game Programming

(C. Jardin) #1
Now comes the interesting work that Levels does. It needs to be able to level
up when the player clears a level. As long as there are more levels, leveling
up should erase the current level, increase the current level number, then
draw the next level. Last, we need to tell the countdown timer to reset, but
with a bit less time.

Levels.prototype.levelUp =function() {
if(!this.hasMoreLevels())return;
this.erase();
this.current_level++;
this.draw();
this.scoreboard.resetCountdown(50 - this.current_level * 5);
};

That’s a nice little method that does exactly what we want it to do. It is tricky
to write code that reads like simple instructions (and sometimes it’s not pos-
sible). But code like that this is something to strive for.

We’re not quite done with the Levels object. The first thing the levelUp() method
does is ask if it has more levels. We need to add that method as follows:

Levels.prototype.hasMoreLevels =function() {
varlast_level = this.levels.length-1;
returnthis.current_level < last_level;
};

If there are two levels in the game, then hasMoreLevels() should be true when
we’re on the first level and false when we’re on the second level. Since Java-
Script likes to start counting from zero, this.current_level will be zero on the first
level and one on the second level. In other words, the last level in a two-level
game would be when this.current_level is one.

Counting from Zero Can Be Difficult

Doing math when you start counting at zero instead of one can be
confusing. It usually helps to plug in real numbers—especially
numbers just before and after the end of a list.

That does it for defining our Levels object. Before we try using it, add the fol-
lowing buildObstacle() method:

functionbuildObstacle(shape_name, x, y) {
varshape;
if(shape_name =='platform') {
shape =newTHREE.CubeGeometry(height/2, height/10, 10);
}else{
shape =newTHREE.CylinderGeometry(50, 2, height);
}

report erratum • discuss

Building Levels • 181


Prepared exclusively for Michael Powell

Free download pdf