Game Development Reference
In-Depth Information
Handling Key and Touch Events
Key and touch events can be handled by overloading the following methods (as shown in Listing 3-9):
onKeyDown : This event fires when a key is pressed. The event receives two
arguments: an integer representing the key code and a KeyEvent . Note that the key
code is an integer value defined by Android not related to the standard ASCII keys.
To test for a specific key, simply compare the value with the static key constants in
KeyEvent .
onKeyUp : This event fires when a key is released, and it receives the same
arguments as onKeUp . Furthermore, you can also check the status of the Shift or Alt
keys using event.isShiftPressed() or event.isAltPressed() respectively.
onTouchEvent : This event fires when you tap the screen, and it receives a
MotionEvent . Tap events have two states: DOWN and UP just like key events. You can
check the tap state by comparing event.getAction() with
MotionEvent.ACTION_DOWN or MotionEvent.ACTION_UP . You can also get the X and Y
coordinates relative to the upper-left corner of the screen.
Listing 3-9. Handling Touch and Key Events
/**
* Android Key events
*/
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
keyUp(keyCode);
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
keyDown(keyCode);
return true;
}
public boolean onTouchEvent(MotionEvent event) {
int tx = (int)event.getX();
int ty = (int)event.getY();
// Has the ship been touched. if so move it
if ( tx >= x && tx <= x + ship.getWidth()
&& ty >= y && ty <= y + ship.getHeight()){
x = tx - (ship.getWidth()/2);
y = ty - (ship.getHeight()/2);
}
// else handle tap
else if ( event.getAction() == MotionEvent.ACTION_UP)
{
Search WWH ::




Custom Search