我正在编写2D RPG游戏,我有一些奇怪的问题。当我使用KeyPressed方法时,它恰好调用我的移动方法两次退出,从[10,11]的[10,10]到[10,12]重写玩家位置并移动我的玩家2个字段。我正在环顾互联网,没有发现任何有用的东西。
为了显示我使用Canvas和Runnable与JFrame。 A也使用Thread
当我使用调试器搜索错误时,我发现Keylistener使用方法 KeyPressed
public void keyPressed(KeyEvent e)
{
((KeyListener)a).keyPressed(e);
((KeyListener)b).keyPressed(e);
}
我相信KeyListener a和b可以解决这个问题,但我不知道解决它的问题。
我的移动方法改变了Point(x,y)
public void move() {
Point startPlayerPosition = player.getPosition();
Point newPoint = startPlayerPosition;
switch (direction) {
case Direction.NORTH:
newPoint = new Point(startPlayerPosition.x, startPlayerPosition.y - 1);
break;
case Direction.SOUTH:
newPoint = new Point(startPlayerPosition.x, startPlayerPosition.y + 1);
break;
case Direction.WEST:
newPoint = new Point(startPlayerPosition.x - 1, startPlayerPosition.y);
break;
case Direction.EAST:
newPoint = new Point(startPlayerPosition.x + 1, startPlayerPosition.y);
break;
}
playerPos = newPoint;
player.setPosition(newPoint);}
这是我的KeyPressed方法。我等待按W,A,S,D来改变方向然后我按照方向调用move()。
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_W:
playerWalk = true;
direction = Direction.NORTH;
move();
break;
case KeyEvent.VK_S:
playerWalk = true;
direction = Direction.SOUTH;
move();
break;
case KeyEvent.VK_D:
playerWalk = true;
direction = Direction.EAST;
move();
break;
case KeyEvent.VK_A:
playerWalk = true;
direction = Direction.WEST;
move();
break;
}
}
感谢您的帮助