2013-03-12 36 views
0

我有一个2人游戏,一个玩家使用WASD,一个使用箭头键。我无法弄清楚如何一次允许多个键。这里是我的代码:多键输入

List keyArray = new ArrayList(); 

    // Red guy input. 
    if (e.getKeyCode() == 37) { // left key 

     new LoadRedCharacter("leftrightfootred.gif"); 

     int x = Frame.redCharacterLabel.getX(); 
     int y = Frame.redCharacterLabel.getY(); 
     if (x < 0) { 
      Frame.redHealthLabel.setLocation(x - 13, y - 15); 
      Frame.redCharacterLabel.setLocation(x + 1, y); 
      ResetEntities.redCharacterObj.setLocation(x + 1, y); 
     } else { 
      Frame.redHealthLabel.setLocation(x - 13, y - 15); 
      Frame.redCharacterLabel.setLocation(x - 2, y); 
      ResetEntities.redCharacterObj.setLocation(x - 2, y); 
     } 
     keyArray.add(37); 
     System.out.println("array" + keyArray); 
     Frame.frame.repaint(); 
     checkHitBox(); 
    } 

我也有蓝色字符左移的代码。然后我有这个:

 // Multi key input 
    if (keyArray.contains(37) && keyArray.contains(65)) { 
     System.out.print("array contains 37 and 65"); 
    } 

为了测试它。但它不起作用。

+1

看看类似的帖子http://stackoverflow.com/questions/2623995/swings-keylistener-and-multiple-keys-pressed-at-the-same-time – 2013-03-12 12:57:17

+0

什么不工作? – 2013-03-12 13:04:23

回答

0

您可以采用多线程方法。有一个线程只关心红色键,另一个线程只关心蓝色。如果您在共享变量上使用同步,它们各自独立行动,不应互相干扰。