我正在为一个类似迷宫的游戏而苦苦挣扎。我正在尝试使用箭头键在 GridPane 中移动“播放器”节点。
这是我的事件处理程序: public class KeyListener implements EventHandler {
public KeyListener(Player player, int prevX, int prevY, GridPane mapGrid) {
this.player = player;
this.prevX = prevX;
this.prevY = prevY;
this.mapGrid = mapGrid;
}
// Method for finding rectangle in gridpane:
private Node getNode(GridPane gridPane, int col, int row) {
for (Node node : gridPane.getChildren()) {
if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) {
return node;
}
}
return null;
}
@Override
public void handle(KeyEvent event) {
try {
System.out.println("Player goes " + event.getCode());
if (event.getCode() == KeyCode.DOWN) {
this.player.setPosX(prevX);
this.player.setPosY(prevY + 1);
Node targetNode = getNode(mapGrid, prevX, prevY+1);
System.out.println(targetNode.toString());
System.out.println(this.player.getPosX() + " " + this.player.getPosY());
mapGrid.add(this.player.playerLook(), player.getPosX(), player.getPosY()); }
仅涵盖按下箭头键时发生的情况。我的问题是节点在第一次按键后向下移动了一行,但在那之后它不再工作了,但是 System.out.println("Player goes " + event.getCode()) 句子被打印出来。
有什么建议么?