Game Development Reference
In-Depth Information
Handling Keyboard Events
You can listen for key presses or releases in Android by simply overriding the methods
onKeyDown
and
onKeyUp
in a view or main activity class. The process can be summarized as
follows (also see Listing 6-7):
onKeyDown
or
onKeyUp
fire in the OpenGL view class
QuakeView
. It is important to note that
Quake handles keys in ASCII format, but Android uses a different
encoding format, so you must use the delegate class
QuakeKeyEvents
to translate them.
When a key is pressed or released, the events
QuakeEvents
translates the key into an ASCII code and
invokes the native method
keyPress
or
keyRelease
, respectively. ASCII
code is then sent to the engine for consumption.
The delegate
keyPress
and
keyRelease
named
Java_quake_jni_Natives_keyPress
and
Java_quake_jni_Natives_
keyRelease
push the ASCII key to the engine queue using
Key_Event
.
The translation of the Android keys to ASCII can be tricky; this is where hardware
fragmentation issues come into play. As you can see in Listing 6-7, an array of integers
(
sKeyCodeToQuakeCode
) is used for key translation, where the index of the array represents
the Android key and the value is the ASCII code. This array works well in the Motorola Droid
1, but it will not be accurate in other devices, as each vendor builds keyboards with different
layouts. Not even among the Motorola Droid versions 1, 2, and 3 are the layouts the same.
This means you may have to adjust the array slightly, depending on what device keyboards
you need to support. Hardware fragmentation is just a fact of life in open platforms.
The companion C implementations for
Listing 6-7. Keyboard Java/C Handlers
// In QuakeView.java
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
queueEvent(new Runnable() {
public void run() {
QuakeKeyEvents.onKeyDown(keyCode, event);
}
});
return true;
}
public boolean onKeyUp(final int keyCode, final KeyEvent event) {
queueEvent(new Runnable() {
public void run() {
QuakeKeyEvents.onKeyUp(keyCode, event);
}
});
return true;
}