Game Development Reference
In-Depth Information
Finally, you add a text label drawn on the belly of the penguin, so the player can see which level
each button refers to:
var textLabel = new Label("Arial", "20px", ID.layer_overlays_1);
textLabel.text = levelIndex + 1;
textLabel.position = new Vector2(this._levelSolved.width - textLabel.width,
this._levelSolved.height - textLabel.height + 50).divideBy(2);
textLabel.color = Color.black;
this.add(textLabel);
In the
handleInput
method, you check whether the button has been pressed. In case of mouse
input, the mouse position should be within the bounding box of the sprite, and the player must have
pressed the left mouse button. If you're dealing with a touch interface, the player's finger should
have pressed within the area of the button on the screen. Finally, the player only can press the
button it if is visible. Here is the complete
handleInput
method:
LevelButton.prototype.handleInput = function (delta) {
if (Touch.isTouchDevice)
this.pressed = this.visible &&
Touch.containsTouchPress(this._levelLocked.boundingBox);
else
this.pressed = this.visible && Mouse.left.pressed &&
this._levelLocked.boundingBox.contains(Mouse.position);
};
If you look at the
LevelButton
class in the
PenguinPairs3
example, it also includes
width
and
height
properties, which you need when you place the level buttons on the screen.
Now that you have a basic
LevelButton
class, you can add the level buttons in the
LevelMenuState
class. In this example, you add 12 level buttons to the menu using a
for
instruction. Depending on
the value of the counter variable (
i
), you calculate the row and column to which the button belongs.
This information, together with the width and the height of a level button, helps you calculate the
final position of each level button:
this.levelButtons = [];
for (var i = 0; i < 12; i += 1) {
var row = Math.floor(i / 5);
var column = i % 5;
var level = new LevelButton(i, ID.layer_overlays);
level.position = new Vector2(column * (level.width + 30) + 155,
row * (level.height + 5) + 230);
this.add(level);
this.levelButtons.push(level);
}
Because later you have to check whether each button has been pressed, you not only add the
buttons to the game state, but also store a reference to each button in an array called
levelButtons
.
This array comes in handy when you want to determine whether the player has clicked one of the
level buttons. You check this in a method called
getSelectedLevel
. This method, which is in the
LevelMenuState
class, iterates over all the level buttons in the array and returns the level index
Search WWH ::
Custom Search