Game Development Reference
In-Depth Information
Because of the assignment instructions inside the method body, you will still create a valid Vector2
object even if you don't pass any parameters when you call the constructor method. If the parameters
x and y are not defined, default values are used. You can use this situation to your advantage, because
relying on default values can lead to much simpler code writing. To give an example, this is the
instruction that draws the background image on the screen:
Canvas2D.drawImage(sprites.background, { x : 0, y : 0 }, 0, { x : 0, y : 0 });
You can make this method call much more compact, by letting the drawImage method automatically
provide default values for the position, rotation and origin parameters:
Canvas2D_Singleton.prototype.drawImage = function (sprite, position,
rotation, origin) {
position = typeof position !== 'undefined' ? position : Vector2.zero;
rotation = typeof rotation !== 'undefined' ? rotation : 0;
origin = typeof origin !== 'undefined' ? origin : Vector2.zero;
// remaining drawing code here
...
}
Drawing the background is then done as follows:
Canvas2D.drawImage(sprites.background);
Although default values for parameters are very useful in creating compact code, make sure that you
always provide documentation for your methods that specify what default values will be used if the
caller of a method doesn't provide all parameters.
What You Have Learned
In this chapter, you have learned:
How to define classes using the prototype mechanism
How to create multiple instances of a type/class
How to add randomness to your game to increase replayability
 
Search WWH ::




Custom Search