在我制作的乒乓球游戏中,我不能同时移动两个球拍

I can't move two paddles at the same time in pong game I am making

所以我尝试在处理中编写乒乓球代码,一切正常,我可以完美地上下移动球拍,但是,当您尝试同时移动两个球拍时,它们不会移动/ 它不允许你(我打算把它做成一个 2 人游戏,这样 2 个人就可以使用相同的键盘玩游戏,但不同的拨片使用不同的键)。

我认为这是使用 "key" 或 "keyPressed" 的问题,因为我认为它无法同时检测到这两者?但我似乎无法弄清楚如何解决这个问题或任何替代方案。 (请记住,我知道如何移动桨叶,只是您不能像我尝试的那样使用提供的不同键同时移动它们)

到目前为止我有两个对象,"Player1" 和 "Player2"

记住 "y" 是 y 位置,它会根据按下的键向上或向下,而 "speed" 只是桨移动的速度。

这是在 Player1 中。上 = w,下 = s

void movement() {

    if(keyPressed) {

      if(key == 'w' || key == 'W') {
        y = y - speed; //goes up

      } else if (key == 's' || key == 'S') {
        y = y + speed; //goes down
      }
    }
  }

这是在Player2中。 Up = 向上箭头键,Down = 向下箭头键

void movement() {

    if (keyPressed) {

      if(key == CODED) {

      if(keyCode == UP) {
        y = y - speed; //goes up

      } else if (keyCode == DOWN) {
        y = y + speed; //goes down
      }

    }

    }

  }

没有错误消息,只是不允许您同时移动 2 个球拍,这是我想做的事情。

您必须使用 keyPressed and keyReleased() 事件。当按下或释放某个键时,事件将执行一次。 按下一个键时设置一个状态,松开键时分别重置状态:

Boolean player1_up = false;
Boolean player1_down = false;
Boolean player2_up = false;
Boolean player2_down = false;

void keyPressed() {
    if (keyCode == UP)
        player1_up = true;
    else if (keyCode == DOWN)
        player1_up = true;
    if (key == 'w' || key == 'W')
        player2_up = true;
    else if (key == 's' || key == 'S')
        player2_down = true;
}

void keyReleasd() {
    if (keyCode == UP)
        player1_up = false;
    else if (keyCode == DOWN)
        player1_up = false;
    if (key == 'w' || key == 'W')
        player2_up = false;
    else if (key == 's' || key == 'S')
        player2_down = false;
}

movement 函数中使用状态 player1_upplayer1_downplayer2_upplayer2_down