Game Development Reference
In-Depth Information
However, this isn't ideal. You now store redundant data, because the color information is represented
by two variables. Furthermore, you might introduce bugs this way if you forget to change one of the
two variables when the color of the cannon changes.
Another way to do it would be to not store a reference to the current sprite. This would be the constructor:
function Cannon() {
this.position = new Vector2(72, 405);
this.colorPosition = new Vector2(55, 388);
this.origin = new Vector2(34, 34);
this.color = Color.red;
this.rotation = 0;
}
This also isn't an ideal approach, because you would need to look up the correct sprite every time
you call the draw method.
One solution is to define two methods that allow users of the Cannon class to retrieve and set the
color information. You can then leave the constructor as is but add methods to read and write a
color value. For example, you could add the following two methods to the Cannon prototype:
Cannon.prototype.getColor = function () {
if (this.currentColor === sprites.cannon_red)
return Color.red;
else if (this.currentColor === sprites.cannon_green)
return Color.green;
else
return Color.blue;
};
Cannon.prototype.setColor = function (value) {
if (value === Color.red)
this.currentColor = sprites.cannon_red;
else if (value === Color.green)
this.currentColor = sprites.cannon_green;
else if (value === Color.blue)
this.currentColor = sprites.cannon_blue;
};
Now the user of the Cannon class doesn't need to know that internally, you use a sprite to determine
the current color of the cannon. The user can simply pass along a color definition to read or write the
color of the cannon:
myCannon.setColor(Color.blue);
var cannonColor = myCannon.getColor();
Sometimes, programmers call these kinds of methods getters and setters . In many object-oriented
programming languages, methods are the only way to access the data inside an object, so for each
member variable that needs to be accessible outside of the class, programmers added a getter and a
setter. JavaScript provides a feature that is relatively new to object-oriented programming languages:
properties . A property is a replacement for a getter and a setter. It defines what happens when you
retrieve data from an object and what happens when you assign a value to data inside an object.
 
Search WWH ::




Custom Search