Java 如何使游戏单元移动到直线对角线上的一点?

Java 如何使游戏单元移动到直线对角线上的一点?,java,game-engine,game-physics,Java,Game Engine,Game Physics,我正在为本学期OOP课的最后一个项目编写一个吃豆人游戏。我已经做了很多,但现在我正在实现一个功能,让鬼魂变成那些“摆动的眼睛”,然后直接回到鬼屋 为了实现这一点,我知道我需要两点:一点是我希望幽灵去哪里(在我的代码中称为幽灵的起始文件),以及幽灵的当前位置。从那里,我们可以计算X/Y距离。我知道我需要按照这些思路做点什么,只是不确定要做什么 这是我目前用于尝试实现此目标的代码: double xDistance = Math.abs(startTile.x*16+8 - position.get

我正在为本学期OOP课的最后一个项目编写一个吃豆人游戏。我已经做了很多,但现在我正在实现一个功能,让鬼魂变成那些“摆动的眼睛”,然后直接回到鬼屋

为了实现这一点,我知道我需要两点:一点是我希望幽灵去哪里(在我的代码中称为幽灵的起始文件),以及幽灵的当前位置。从那里,我们可以计算X/Y距离。我知道我需要按照这些思路做点什么,只是不确定要做什么

这是我目前用于尝试实现此目标的代码:

double xDistance = Math.abs(startTile.x*16+8 - position.getCenterX());
double yDistance = Math.abs(startTile.y*16+8 - position.getCenterY());
double xRatio = xDistance / yDistance;
double yRatio = yDistance / xDistance;
if((int)Math.round(startTile.x*16+8) < (int)Math.round(position.getCenterX())) {
  position.setDirection(DIRECTION_WEST);
  position.step(movementPixels*xRatio);
} else if((int)Math.round(startTile.x*16+8) > (int)Math.round(position.getCenterX())) {
  position.setDirection(DIRECTION_EAST);
  position.step(movementPixels*xRatio);
}
if((int)Math.round(startTile.y*16+8) < (int)Math.round(position.getCenterY())) {
  position.setDirection(DIRECTION_NORTH);
  position.step(movementPixels*yRatio);
} else if((int)Math.round(startTile.y*16+8) > (int)Math.round(position.getCenterY())) {
  position.setDirection(DIRECTION_SOUTH);
  position.step(movementPixels*yRatio);
}
System.out.println(position.getTileX() + " == " + startTile.x + " && " + position.getTileY() + " == " + startTile.y);
if(position.getTileX() == startTile.x && position.getTileY() == startTile.y) {
  setNewLife();
}
double-xDistance=Math.abs(startTile.x*16+8-position.getCenterX());
double yddistance=Math.abs(startTile.y*16+8-position.getCenterY());
双X比=X距离/Y距离;
双Y轴=Y轴距离/X轴距离;
if((int)Math.round(startTile.x*16+8)<(int)Math.round(position.getCenterX()){
位置设置方向(西向);
位置步进(移动像素*xRatio);
}else如果((int)Math.round(startTile.x*16+8)>(int)Math.round(position.getCenterX()){
位置。设置方向(向东);
位置步进(移动像素*xRatio);
}
if((int)Math.round(startTile.y*16+8)<(int)Math.round(position.getCenterY()){
位置设置方向(北向);
位置步进(移动像素*yRatio);
}else如果((int)Math.round(startTile.y*16+8)>(int)Math.round(position.getCenterY()){
位置。设置方向(南方向);
位置步进(移动像素*yRatio);
}
System.out.println(position.getTileX()+“=”+startTile.x+“&&&“+position.getTileY()+”=”+startTile.y);
if(position.getTileX()==startTile.x&&position.getTileY()==startTile.y){
setNewLife();
}
不幸的是,这不起作用。事实上,它们的移动非常怪异,最终会射向地图的某个地方,在这一点上,position.getTileY()将返回一个值,如2173454或其他疯狂的值


任何帮助都将不胜感激

这不是问题的解决方案(仍在研究中),但您可以将
startTile.x*16+8
position.getCenterX()
startTile.y*16+8
position.getCenterY()
的值存储在变量中,这样您就不必在对函数的一次调用中多次计算每个值。您还可以更进一步,将舍入的值存储在变量中。您可以为一些迭代发布初始条件和最后一个
System.out.println
语句的输出吗?