【发布时间】:2023-03-20 16:20:01
【问题描述】:
所以我正在尝试创建一个有点像蛇的 Tron 多人游戏。 无论如何,多人应该能够使用一个键盘玩该游戏,但不同的组合键可以在屏幕上引导他们的角色。一位玩家目前使用 WASD 键,另一位玩家应使用箭头键。
我的问题是我使用 FXML 使用 Javafx Scene Builder 创建了一个场景。在创建游戏之后我才注意到场景构建器显然只支持一个按键监听器,所以目前只有一个玩家可以控制他们的游戏人物。 有没有办法解决这个问题?请帮助一位玩家可以使用 WASD 键,而另一位玩家可以使用箭头键进行导航。 我的问题与现有解决方案不同,因为蛇需要属于不同的玩家。仅检查是否按下了一个键输入或同时按下了两个键是不够的,但它需要检查是否正确的玩家按下了输入,即使当时另一个玩家也按下了他们的输入。 希望这能消除一些混乱。
关键监听器
import java.util.ArrayList;
import javafx.scene.Scene;
public class Human extends Player implements Runnable{
int keyboardControlsLayout;
Scene scene;
public Human(int stepSize, String colour, int playerNum, Scene scene,
int keyboardControlsLayout) {
super(stepSize, colour, playerNum);
// keyboardControlsLayout(0) = WASD
// keyboardControlsLayout(1) = ARROWS
this.keyboardControlsLayout = keyboardControlsLayout;
this.scene = scene;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(this.getSnake().getAlive()) {
if (keyboardControlsLayout == 1) {
// use WASD
System.out.println("wasd");
scene.setOnKeyPressed(event -> {
switch (event.getCode()) {
case W:
snake.setDirection(0);
break;
case S:
snake.setDirection(1);
break;
case A:
snake.setDirection(3);
break;
case D:
snake.setDirection(2);
break;
default:
break;
}
//System.out.println(event.getCode().toString());
});
} else if (keyboardControlsLayout == 0) {
System.out.println("arrows");
// use arrow keys
scene.setOnKeyPressed(event -> {
switch (event.getCode()) {
case UP:
snake.setDirection(0);
break;
case DOWN:
snake.setDirection(1);
break;
case LEFT:
snake.setDirection(3);
break;
case RIGHT:
snake.setDirection(2);
break;
default:
break;
}
});
}
}
}
}
我在哪里创建场景:
public void newGame() {
System.out.println("<----- NEW GAME ----->");
game = new Game(10, scene, numHumans);
displayController.setUpDisplay(game);
timer = new Timeline((new KeyFrame(
Duration.millis(80),
event -> {
try {
timerTick();
} catch (Exception e) {
// TODO Auto-generated catch
block
e.printStackTrace();
}
})));
timer.setCycleCount(Animation.INDEFINITE);
start();
}
private void start() {
// starts game and logic
}
private void loadDisplayFXMLLoader() {
FXMLLoader displayFXMLLoader = new
FXMLLoader(getClass().getResource("DisplayView.fxml"));
try {
scene = new Scene(displayFXMLLoader.load(), 500, 525);
} catch (IOException e) {
Main.outputError(e);
}
displayController = displayFXMLLoader.getController();
}
private void loadScene() {
this.setScene(scene);
this.show();
//error Handling and closing
}
任何帮助将不胜感激!
谢谢
【问题讨论】:
-
我喜欢使用here 找到的想法。他使用
ArrayList进行输入。我喜欢使用Set。当按下映射按钮时,将其添加到输入中。发布时,将其从输入中删除。 -
它与您指出的问题类似。但不完全相同,因为我不想同时按下多个键。但是听众可能会对两个玩家做出反应
-
我会看看那个。谢谢塞德里克!
-
我没有在副本中使用@James_D 答案,但考虑到他的历史,我敢打赌它有效。我在共享的链接上使用了第一个想法。它工作正常。
标签: java javafx keylistener