Game Development Reference
In-Depth Information
For cannons, this method doesn't do exactly what you want. You want to draw the color of the
cannon, but you also want to draw the cannon barrel. Replacing a method is very easy. You simply
redefine the method as a part of the Cannon prototype:
Cannon.prototype.draw = function () {
if (!this.visible)
return;
var colorPosition = this.position.subtract(this.size.divideBy(2));
Canvas2D.drawImage(sprites.cannon_barrel, this.position, this.rotation, 1,
this.origin);
Canvas2D.drawImage(this.currentColor, colorPosition);
};
In object-oriented jargon, when you replace a method inherited from the superclass in the
subclass, you say that you override the method. In this case, you override the draw method from
ThreeColorGameObject . Similarly, if you wanted to, you could override a property, or even remove
properties and methods by letting them refer to undefined . Once a Cannon object has been created,
you have the full flexibility that JavaScript offers to modify that object.
Note Even though you're overriding a method in this example, JavaScript doesn't use an override
keyword as is common in other languages such as Java or C#.
If you take a look at the Cannon.js file in the Painter9 example belonging to this chapter, you can
see that the Cannon class definition is much smaller and easier to read than in the previous version,
because all the generic game-object members are placed in the ThreeColorGameObject class.
Organizing your code in different classes and subclasses helps to reduce code copying and results
in generally cleaner designs. There is a caveat, however: your class structure (which class inherits
from which other class) must be correct. Remember that classes should only inherit from other
classes if there is a “is a kind of” relationship between the classes. To illustrate this, suppose you
would like to add an indicator at the top of the screen that shows which color the ball currently is.
You could make a class for that and let it inherit from the Cannon class because it needs to handle
input in a similar way:
function ColorIndicator() {
Cannon.call(this, ...);
// etc.
}
However, this is a very bad idea. A color indicator is certainly not a kind of cannon, and designing
your classes this way makes it very unclear to other developers what the classes are used for.
Furthermore, the color indicator would also have a rotation, which doesn't make any sense.
Class-inheritance diagrams should be logical and easy to understand. Every time you write a class
that inherits from another class, ask yourself whether that class really “is a kind of” the class that you
inherit from. If it isn't, then you have to rethink your design.
 
Search WWH ::




Custom Search