2

I am programming a game and need to execute two keyEvents before fire();

For now I have done this to test:

if (key == KeyEvent.VK_SPACE) {
    fire();
}

What I need is:

if (key == KeyEvent.VK_DOWN) && (key == KeyEvent.VK_UP) {
    fire();
}

The problem is, they need to be pressed in this sequence: First down, then up and so fire, but I don't know how can I do it.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
Anderson
  • 59
  • 1
  • 7
  • Maintain a series of flags which indicate which keys are pressed. I'd also recommend using the key bindings API over `KeyListener`, see [How to Use Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) for more details – MadProgrammer Nov 10 '14 at 23:47

2 Answers2

2

Keep track of time and key pressed for last 4 events in a FIFO, and see the history to decide

jmj
  • 237,923
  • 42
  • 401
  • 438
0

I think the best way to do it is to implement a KeyListener (an example is here) in order to recognize exactly which event has occurred. For example you could use a boolean variable (i.e. readyToFire) to store whether the

 `KeyEvent.VK_UP`

event produces or not a fire one. For instance a possible implementation may be:

    //boolean readyToFire = false;

    public void keyTyped(KeyEvent e) {
         if(e == KeyEvent.VK_UP && readyToFire){
              fire();
         }
    }

    public void keyPressed(KeyEvent e) {
         if(e == KeyEvent.VK_DOWN){
              readyToFire = true;
         }
         else if(e == KeyEvent.VK_UP && readyToFire){
              fire();
         }
    }

    public void keyReleased(KeyEvent e) {
         if(e == KeyEvent.VK_DOWN){
              readyToFire = false;
         }
    }
Community
  • 1
  • 1
Lemm Ras
  • 992
  • 7
  • 18