Game Development Reference
In-Depth Information
Let's look at this ThreeColorGameObject class in more detail. You put into this class the member
variables that are commonly used by the different types of game objects in the game. You can define
a basic skeleton of this class as follows:
function ThreeColorGameObject() {
this.currentColor = undefined;
this.velocity = Vector2.zero;
this.position = Vector2.zero;
this.origin = Vector2.zero;
this.rotation = 0;
this.visible = true;
}
Each class that inherits from ThreeColorGameObject will have a velocity, a position, an origin, a
rotation, and so on. This is nice, because now you only define these member variables in one place,
and they can be used in any class that inherits from ThreeColorGameObject .
One thing that is still missing in this constructor is a way to deal with the three different colors. In the
case of Painter, each game-object type has three different sprites, each one representing a different
color. When you define the ThreeColorGameObject class, you don't know yet which sprites to use,
because they will depend on the final type of the game object (cannons use sprites other than balls
or paint cans). In order to solve this, let's extend the constructor as follows:
function ThreeColorGameObject(sprColorRed, sprColorGreen, sprColorBlue) {
this.colorRed = sprColorRed;
this.colorGreen = sprColorGreen;
this.colorBlue = sprColorBlue;
this.currentColor = this.colorRed;
this.velocity = Vector2.zero;
this.position = Vector2.zero;
this.origin = Vector2.zero;
this.rotation = 0;
this.visible = true;
}
Whenever you inherit from this class, you can define what the values of the member variables
colorRed , colorGreen ,and colorBlue should be.
Now you need to define the basic game-loop methods. The method for drawing the game object is
straightforward. You probably noted that a member variable visible is added to the class. You can
use this member variable to toggle the visibility of game objects. In the draw method, you draw the
sprite on the screen only if the game object should be visible:
ThreeColorGameObject.prototype.draw = function () {
if (!this.visible)
return;
Canvas2D.drawImage(this.currentColor, this.position, this.rotation, 1,
this.origin);
};
 
Search WWH ::




Custom Search