2013-12-19 50 views
1

我需要设计一个双人游戏。每个球都有球,应该能够将球移动到右或左,第一个球员有'a''d'按钮,第二个球员有右,左箭头按钮。然而,目前一名球员需要等待另一名球员的动作完成才能移动自己的球。我如何解决这个问题?这里是我的代码的相关部分:我怎样才能让多个键绑定同时工作?

public class AnimationWindow extends JPanel{ 

     public AnimationWindow() 
     { 

      super(); 
      .... 
      .... 
      cezmiMover(); 

     } 



public void cezmiMover(){ 

     this.getInputMap().put(KeyStroke.getKeyStroke('a'), "left1"); 
     this.getActionMap().put("left1", new AbstractAction() { 

      public void actionPerformed(ActionEvent e) { 

       board.cezmi1.moveLeft(); 
      } 
     }); 

     this.getInputMap().put(KeyStroke.getKeyStroke('d'), "right1"); 
     this.getActionMap().put("right1", new AbstractAction() { 

      public void actionPerformed(ActionEvent e) { 

       board.cezmi1.moveRight(); 
      } 
     }); 

     this.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "left2"); 
     this.getActionMap().put("left2", new AbstractAction() { 

      public void actionPerformed(ActionEvent e) { 

       board.cezmi2.moveLeft(); 
      } 
     }); 

     this.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "right2"); 
     this.getActionMap().put("right2", new AbstractAction() { 

      public void actionPerformed(ActionEvent e) { 

       board.cezmi2.moveRight(); 
      } 
     }); 
    } 
} 

回答

7

您需要使用一系列标志和某种“更新”循环更新的游戏取决于标志的状态的状态...

例如,通过创建一系列标志的开始......

private boolean p1Left, p1Right, p2Left, p2Right = false; 

这些可以很容易地通过个别球员的对象保持不变,但你没有提供太多的代码...

接下来,你需要监视按键和键释放事件,并根据需要设置相应标志的状态...

this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "right1down"); 
this.getActionMap().put("right1down", new AbstractAction() { 
    public void actionPerformed(ActionEvent e) { 
     p1Right = true; 
    } 
}); 

this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, true), "right1up"); 
this.getActionMap().put("right1up", new AbstractAction() { 
    public void actionPerformed(ActionEvent e) { 
     p1Right = false; 
    } 
}); 

然后,你需要某种循环或定时器,可以更新游戏的状态。就个人而言,我喜欢使用javax.swing.Timer,但那只是我。

上的更新循环的每个运行,您需要检查每个标志的状态,并相应地更新对象...

if (p1Right) { 
    board.cezmi1.moveRight(); 
} 

对于example

3

退房Motion Using the KeyboardKeyboardAnimation.java代码包含一个完整的工作示例,演示了执行此操作的一种方法。

的KeyboardAnimation类的每个实例:

  1. 动画使用定时器
  2. 动画由分配将KeyStroke控制
  3. 一个地图跟踪已​​压到它击键的成分(JLabel的)同时处理多个KeyStrokes
相关问题