Game Development Reference
In-Depth Information
Because Cannon inherits from ThreeColorGameObject , you need to call the constructor of the
ThreeColorGameObject class. This constructor expects three parameters. Because you're creating a
Cannon object, you want to pass the colored cannon sprites to that constructor. Fortunately, you can
pass along these sprites in the call method, as follows:
ThreeColorGameObject.call(this, sprites.cannon_red, sprites.cannon_green,
sprites.cannon_blue);
Second, you set the position and the origin of the cannon, just as you did in the original Cannon class:
this.position = new Vector2(72, 405);
this.origin = new Vector2(34, 34);
The rest of the work (assigning the three color sprites and initializing the other member variables)
is done for you in the ThreeColorGameObject constructor! Note that it's important to first call the
constructor of the superclass before setting the member variables in the subclass. Otherwise,
the position and origin values you choose for the cannon will be reset to zero when the
ThreeColorGameObject constructor is called.
Now that the new version of the Cannon class has been defined, you can start adding properties and
methods to the class, just as you did before. For example, here is the handleInput method:
Cannon.prototype.handleInput = function (delta) {
if (Keyboard.down(Keys.R))
this.currentColor = this.colorRed;
else if (Keyboard.down(Keys.G))
this.currentColor = this.colorGreen;
else if (Keyboard.down(Keys.B))
this.currentColor = this.colorBlue;
var opposite = Mouse.position.y - this.position.y;
var adjacent = Mouse.position.x - this.position.x;
this.rotation = Math.atan2(opposite, adjacent);
};
As you can see, you can access member variables such as currentColor and rotation without
any problem. Because Cannon inherits from ThreeColorGameObject , it contains the same member
variables, properties, and methods.
Overriding Methods from the Superclass
In addition to adding new methods and properties, you can also choose to replace a method in the
Cannon class. For example, ThreeColorGameObject has the following draw method:
ThreeColorGameObject.prototype.draw = function () {
if (!this.visible)
return;
Canvas2D.drawImage(this.currentColor, this.position,
this.rotation, 1, this.origin);
};
 
Search WWH ::




Custom Search