3D Game Programming

(C. Jardin) #1
This method will take a list of things that belong to a new level. That list will
include everything that needs to be shown when the player reaches the level.
It’s also everything that needs to be removed when the player completes the
level. We push this onto the list of all levels. If push seems like a strange name
to you, you’re not alone. Sometimes we programmers have to remember
strange names.

Next we need a quick way to get the objects defined for the current level:


Levels.prototype.thingsOnCurrentLevel =function() {
returnthis.levels[this.current_level];
};

Remember that computers like counting from zero. If the current level is zero,
then this method will return this.levels[0], which is another way of looking up
the first item in a list.

Next, we need to be able to draw the current level on the scene:


Levels.prototype.draw =function() {
varscene = this.scene;
this.thingsOnCurrentLevel().forEach(function(thing) {
scene.add(thing);
});
};

We use the thingsOnCurrentLevel() method that we just created to get a list of the
things we need to draw. Then we say that, for each of those, we want to run
a function that adds the thing to the scene.

Functions Can Do the Unexpected to this
JavaScript functions can do strange things to this, which is why we
make a copy of the scene variable. In Project: Learning about Java-
Script Objects, we saw that this normally refers to the current object.
That is true, except inside functions. Inside a function, like the one
we use to add things to the scene, this refers to the function itself.
To deal with this JavaScript quirk, programmers normally make a
copy of this (or one of its properties) before a function call.

If we have a way to draw objects, then we need a way to erase them:


Levels.prototype.erase =function() {
varscene = this.scene;
this.thingsOnCurrentLevel().forEach(function(obstacle) {
scene.remove(obstacle);
});
};

Chapter 19. Project: Multilevel Game • 180


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf