Game Development Reference
In-Depth Information
Note that you only handle input if the button is visible. In the PenguinPairsGameWorld class, you add
an OnOffButton instance to the game world, at the desired position:
this.onOffButton = new OnOffButton(sprites.button_offon, ID.layer_overlays);
this.onOffButton.position = new Vector2(650, 340);
this.onOffButton.on = GameSettings.hints;
this.add(this.onOffButton);
In this example, you're using a variable GameSettings , in which you store any settings related to
the game. In this case, you maintain a setting that indicates whether you should show a hint on the
screen. Later, the chapter discusses this in more detail.
Adding a Slider Button
Next you add a second kind of GUI control: a slider. This slider will control the volume of the background
music in the game. It consists of two sprites: a back sprite that represents the bar, and a front sprite that
represents the actual slider. Therefore, the Slider class inherits from GameObjectList . Because the back
sprite has a border, you need to take that into account when you move or draw the slider. Therefore,
you also define left and right margins that define the border width on the left and right side of the back
sprite. You also position the slider slightly lower than the back sprite, to account for the top border.
The complete constructor is as follows:
function Slider(sliderback, sliderfront, layer) {
GameObjectList.call(this, layer);
this.dragging = false;
this.draggingId = -1;
this.leftmargin = 5;
this.rightmargin = 7;
this.back = new SpriteGameObject(sliderback);
this.front = new SpriteGameObject(sliderfront, 1);
this.front.position = new Vector2(this.leftmargin, 8);
this.add(this.back);
this.add(this.front);
}
As you can see, you also set a Boolean variable dragging to false and a variable draggingId to -1.
You need these variable to keep track of when the player is dragging the slider and what the touch
ID is so you update the slider position when needed, even when the mouse pointer / touch position
isn't within the boundaries of the back sprite.
The next step is adding a property value that allows you to retrieve and set the value of the slider.
You want a value of 0 to indicate that the slider is fully moved to the left, and a value of 1 to indicate
the fully right position of the slider. You can calculate the current value by looking at the position of
the front sprite, and seeing how much it's moved to the right. Therefore, the following line of code
calculates the slider value from the slider position:
return (this.front.position.x - this.back.position.x - this.leftmargin) /
(this.back.width - this.front.width - this.leftmargin - this.rightmargin);
 
Search WWH ::




Custom Search