Game Development Reference
In-Depth Information
else {
this.color = Game.gameWorld.cannon.color;
this.position = Game.gameWorld.cannon.ballPosition
.subtractFrom(this.center);
}
if (Game.gameWorld.isOutsideWorld(this.position))
this.reset();
};
Look at the first instruction in this method. You're accessing the prototype object of
ThreeColorGameObject , which contains an update function. You call this update function while
passing the this object, so the Ball object is updated, but according to the update method defined
in ThreeColorGameObject . Finally, you pass the delta parameter to that call. The nice thing is that
this approach allows you to separate different parts of (in this case) the updating process. Any game
object with a position and velocity will need to update its position based on its velocity in each
iteration of the game loop. You define this behavior in the update method of ThreeColorGameObject
so you can reuse it for any class that inherits from ThreeColorGameObject !
Polymorphism
Because of the inheritance mechanism, you don't always have to know to what type of object a
variable is pointing to. Consider the following declaration and initialization:
var someKindOfGameObject = new Cannon();
And somewhere else in the code, you do this:
someKindOfGameObject.update(delta);
Now suppose you change the declaration and initialization, as follows:
var someKindOfGameObject = new Ball();
Do you need to change the call to the update method? No, you don't, because the way the
game-loop methods are being called is defined in the ThreeColorGameObject class. When you call
the update method on the someKindOfGameObject variable, it doesn't matter which game object it
actually refers to. The only thing that is important is that the update method is defined and that it
expects a single parameter: the time passed since the last update call. Because the interpreter
keeps track of which object it is, the right version of the update method is called automatically.
This effect is called polymorphism , and it comes in very handy sometimes. Polymorphism allows you
to better separate code. Suppose a game company wants to release an extension of its game. For
example, it might want to introduce a few new enemies, or skills that a player can learn. The company
can provide these extensions as subclasses of generic Enemy and Skill classes. The actual game
code will then use these objects without having to know which particular skill or enemy it's dealing
with. It simply calls the methods that were defined in the generic classes.
 
Search WWH ::




Custom Search