在java中同时按下两个键

时间:2016-05-23 14:19:19

标签: java swing

我正在开发一个包含两个玩家的简单2D游戏。我用按键W,A,S和D移动玩家1.其他玩家由箭头键控制。

我面临的问题是,当按住任何箭头键移动播放器2时,按键W,S,D和A对播放器1起作用,反之亦然。

我已经看到了this之类的答案,但它没有解决我的问题。

我有一个主类Gameplay,并制作了两个内部类Player1Listener和Player2Listener(实现KeyListener)。

一个类的示例代码如下所示,其他子类看起来相同。

private class Player1Listener implements KeyListener
{
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}      
    public void keyPressed(KeyEvent e) {    
        if(e.getKeyCode()== KeyEvent.VK_W)
        {
            player1right = false;
            player1left = false;
            player1down = false;
            player1up = true;       

            player1Y-=10;

        }
        if(e.getKeyCode()== KeyEvent.VK_A)
        {
            player1right = false;
            player1left = true;
            player1down = false;
            player1up = false;

            player1X-=10;
        }
        if(e.getKeyCode()== KeyEvent.VK_S)
        {
            player1right = false;
            player1left = false;
            player1down = true;
            player1up = false;

            player1Y+=10;
        }
        if(e.getKeyCode()== KeyEvent.VK_D)
        {
            player1right = true;
            player1left = false;
            player1down = false;
            player1up = false;

            player1X+=10;
        }
    }
}

我在Gameplay构造函数中添加了这些关键的侦听器,如

addKeyListener(new player1Listener());

1 个答案:

答案 0 :(得分:1)

    private final Set<Character> Keyspressed = new HashSet<Character>(); 

    public void keyPressed(KeyEvent e){
            pressed.add(e.getKeyChar());
            if (Keyspressed.size() > 1) {
    //size is greator than one which means you
    //have pressed more than one key. 
    //now your set contains all pressed keys. iterate it and fine out which was pressed.
                   foo(Keyspressed);
                    }
                }
    public void foo(Set<Character> Keyspressed){
    boolean Apressed = false;
    boolean Wpressed = false;
    boolean Spressed = false;
    boolean Dpressed = false;

      for(Character e : Keyspressed){
      if(e==KeyEvent.VK_A){
      Apressed = true; 
      }else if(e==KeyEvent.VK_S){
      Spressed = true;
      }else if(e==KeyEvent.VK_D){
      Dpressed = true; 
      }else if(e==KeyEvent.VK_W){
      Wpressed = true;
        }
      } 
      if(Apressed && Spressed){
      //your logic
         }

      }

您可以将所有按下的键添加到set<Character>中并实现一个函数来迭代按下的键。