Game Development Reference
In-Depth Information
Adding an On/off Button
The next step is adding an on/off button that shows a hint (or doesn't) during game play. Later in
the chapter, you see how the value of this button is used. Just as you did for the Button class in the
Jewel Jam game, you make a special class for on/off buttons, called (not surprisingly) OnOffButton .
The class is a subclass of SpriteGameObject , and it expects a sprite strip containing two sprites: one
for the off state and one for the on state (see Figure 19-1 ).
Figure 19-1. The sprite strip used for the on/off button
An important aspect of the button is that you need to be able to read and set whether it's on or off.
Because the button is based on a sprite strip of length two, you can define that the button is in the
off state if the sheet index is 0, and that it's in the on state if the sheet index equals 1. You can then
add a boolean property that gets and sets this value. Here is the definition of that property:
Object.defineProperty(OnOffButton.prototype, "on",
{
get: function () {
return this.sheetIndex === 1;
},
set: function (value) {
if (value)
this.sheetIndex = 1;
else
this.sheetIndex = 0;
}
});
Finally, you need to handle mouse clicks on the button to toggle its on and off states. Similar to
what you did in the Button class, you check in the handleInput method whether the left mouse
button was pressed and whether the mouse position is within the bounding box of the button. For
touch input, you follow a similar procedure. If the player has pressed the button, you need to modify
the sheet index. If the sheet index is 0, it should become 1, and vice versa. Here is the complete
handleInput method:
OnOffButton.prototype.handleInput = function (delta) {
if (!this.visible)
return;
if (Touch.containsTouchPress(this.boundingBox) ||
Mouse.containsMousePress(this.boundingBox))
this.sheetIndex = 1 - this.sheetIndex;
};
 
Search WWH ::




Custom Search