1

I am new to android development, making a simple game and using onKeyDown(.....) function but it works only for 1 key at a time, how to handle 2 keys at a time means can i move right or left with continous firing.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    switch (keyCode){
    case KeyEvent.KEYCODE_DPAD_RIGHT:

        bottle_movx+=2;

    break;
    case KeyEvent.KEYCODE_DPAD_LEFT:

        bottle_movx-=2;
        break;

    case KeyEvent.KEYCODE_DPAD_DOWN:
        fire=bottle_movx;
        firechk=true;
        break;      

    }

    invalidate();
    return super.onKeyDown(keyCode, event);

}
Raaz
  • 9
  • 1
  • 3

2 Answers2

2

EDIT: Perhaps this could be of some help? How do I handle simultaneous key presses in Java?

Quote: One way would be to keep track yourself of what keys are currently down. When you get a keyPressed event, add the new key to the list; when you get a keyReleased event, remove the key from the list. Then in your game loop, you can do actions based on what's in the list of keys.

EDIT 2: I also found this link which could be useful: How do I handle multiple key presses in a Java Applet?

Community
  • 1
  • 1
span
  • 5,405
  • 9
  • 57
  • 115
  • KeyCode will have one value at a time , so if we press two keys we should have 2 values which is not possible in switch case,i also use use if else but still not working. – Raaz Dec 15 '11 at 08:50
  • Each key should only trigger one key event so there should only be one keycode for each event though...or? – span Dec 15 '11 at 09:05
  • Is there any other function() or any other technique to do this (pressing two keys at a time) ?? – Raaz Dec 15 '11 at 10:00
  • I'm not sure. To find out you could create a simple while loop that constantly prints out the key you are pressing. You can then see if the second key event ever gets through while the first key is pressed. If it gets through you should be fine. If it doesn't perhaps you need to rethink the gameplay :/ – span Dec 15 '11 at 11:02
  • Perhaps this can help you? http://stackoverflow.com/questions/752999/how-do-i-handle-multiple-key-press-in-java – span Dec 15 '11 at 11:05
1

Please also check the action event( event.getAction() ). This would return the constant defined in the KeyEvent class like ACTION_DOWN, ACTION_UP etc. Please check for either up or down action.

Praful Bhatnagar
  • 7,425
  • 2
  • 36
  • 44
  • ACTION_DOWN, will work for every key when it is pressed. I need to get 2 keys of my own choice. like left, right, and any other fire key. – Raaz Dec 15 '11 at 11:01