Game Development Reference
In-Depth Information
int
len = touchEvents.size();
for
(
int
i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if
(event.type == TouchEvent.
TOUCH_UP
) {
if
if(inBounds(event, 0, g.getHeight() - 64, 64, 64)) {
Settings.
soundEnabled
= !Settings.
soundEnabled
;
if
(Settings.
soundEnabled
)
Assets.
click
.play(1);
}
if
if(inBounds(event, 64, 220, 192, 42) ) {
game.setScreen(
new
GameScreen(game));
if
(Settings.
soundEnabled
)
Assets.
click
.play(1);
return
;
}
if
if(inBounds(event, 64, 220 + 42, 192, 42) ) {
game.setScreen(
new
HighscoreScreen(game));
if
(Settings.
soundEnabled
)
Assets.
click
.play(1);
return
;
}
if
if(inBounds(event, 64, 220 + 84, 192, 42) ) {
game.setScreen(
new
HelpScreen(game));
if
(Settings.
soundEnabled
)
Assets.
click
.play(1);
return
;
}
}
}
}
Next, we have the
update()
method, in which we'll do all our touch event checking. We first
fetch the
TouchEvent
and
KeyEvent
instances from the
Input
instance the
Game
provides us.
Note that we do not use the
KeyEvent
instances, but we fetch them anyway in order to clear
the internal buffer (yes, that's a tad bit nasty, but let's make it a habit). We then loop over all
the
TouchEvent
instances until we find one with the type
TouchEvent.TOUCH_UP
. (We could
alternatively look for
TouchEvent.TOUCH_DOWN
events, but in most UIs the up event is used to
indicate that a UI component was pressed.)
Once we have a fitting event, we check whether it pressed either the sound toggle button or one of
the menu entries. To make that code a little cleaner, we wrote a method called
inBounds()
, which
takes a touch event, x and y coordinates, and a width and height. The method checks whether the
touch event is inside the rectangle defined by those parameters, and it returns either
true
or
false
.
If the sound toggle button is pressed, we simply invert the
Settings.soundEnabled
Boolean
value. In case any of the main menu entries are pressed, we transition to the appropriate screen
by instancing it and setting it via
Game.setScreen()
. We can immediately return in that case, as
the
MainMenuScreen
doesn't have anything to do anymore. We also play the click sounds if either
the toggle button or a main menu entry is pressed and sound is enabled.
Remember that all the touch events will be reported relative to our target resolution of
320 × 480 pixels, thanks to the scaling magic we performed in the touch event handlers
discussed in Chapter 5.