Java:每次按下只识别一次keyPressed

时间:2014-12-09 18:01:18

标签: java keylistener

我正在用Java制作游戏,我希望能够走到NPC并按空间与他们交谈。但是,我现在的KeyBoard课程面向的是移动键(在左下方是向上和向上),它始终识别出按键以保持玩家的移动。如何设置它以便空格键只有在被按下后才会被识别,并且在播放器释放并再次按下之前不会被识别?

public class Keyboard implements KeyListener
{

    private boolean[] keys = new boolean[120];

    public boolean up, down, left, right, interact;

    public void update() 
    {
        up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W];
        down = keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S];
        left = keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A];
        right = keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D];
        interact = keys[KeyEvent.VK_SPACE];
    }

    public void keyPressed(KeyEvent e) 
    {
        keys[e.getKeyCode()] = true;
    }

    public void keyReleased(KeyEvent e) 
    {
        keys[e.getKeyCode()] = false;
    }
}

1 个答案:

答案 0 :(得分:2)

Set<Integer> pressedKeys = new TreeSet<Integer>();

public void keyPressed(KeyEvent ke) {
  int code = ke.getKeyCode();
  Integer val = Integer.valueOf(code);
  if (pressedKeys.contains(val)) {
    //we've already pressed the key and it is being held down
    return;
  }
  else {
    //process key event
  }
}

public void keyReleased(KeyVEnt ke) {
  pressedKeys.remove(ke.getKeyCode());
}