You can get the key pressed events from your activities view. Override the KeyDown and KeyUp events like this:
@Override
public boolean onKeyDown(int keyCode, KeyEvent msg) {
if (keyCode==KeyEvent.KEYCODE_DPAD_LEFT) { //DO CODE FOR LEFT KEY PRESSED
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent msg) {
}
The KeyEvent class has constants for all the buttons keycodes:
http://developer.android.com/reference/android/view/KeyEvent.htmlFor the arrow buttons you would use KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, AND KeyEvent.KEYCODE_DPAD_CENTER
Not all phones have a directional key pad. For these phones you want to add a way to navigate the ship. You could let them use the A, D, S, W like Eric said, though some phones don't have a keyboard at all so you need to add touch or tilt controls as well. The best way to do it, is let the player choose which kind of controls he wants. You can even let them assign their own keys to the actions. You could have an options screen that asks them to choose/press which key to move the ship up. Then when they press a key save the keyCode they pressed as an integer, then when they are playing check to see if the keyCodes they are pressing matches one of the integers you saved.
Like this:
@Override
public boolean onKeyDown(int keyCode, KeyEvent msg) {
//Psuedo coding here, you would integrate this into your own options settings.
if (state==CHOOSELEFTKEY) {
userSettingsLeftKey=keyCode;
}
if (state==playingGame) {
if (keyCode==userSettingsLeftKey) { //DO CODE FOR LEFT KEY PRESSED
}
}
— modified on Feb 23, 2012, 4:31:49 AM
Recommended editorial content
With your consent, external content is loaded here.
By clicking on the button above, you agree that external content may be displayed to you. Personal data may be transmitted to third-party providers in the process. You can find more information about this in our Privacy Policy.