我正在制作类似于tank
的Atari tank game
游戏,但遇到了一些麻烦。我正在尝试制作enemy's tank move towards the player's tank
,但我想制作can't move diagonally
,因为不允许播放器也这样做。但是,按照我的实现方式,当距x和y轴的距离相等时,它会倾斜。有什么方法可以使它在改变方向后被迫沿一个方向移动一会儿吗?这样做的方式是将其与玩家的战车(传递中的战车)一起使用compare its x and y values
,四种情况是x-component is bigger than y
是否在right or left
上,以及y-component is bigger than x
及其是否在玩家的战车above or below
上。感谢您的帮助!
public void enemyMove(Tank t) {
if ( Math.abs(getX() - t.getX()) >= Math.abs(getY() - t.getY()) && getX() > t.getX() )
goLeft();
else if ( Math.abs(getX() - t.getX()) > Math.abs(getY() - t.getY()) && getX() < t.getX() )
goRight();
else if ( Math.abs(getX() - t.getX()) <= Math.abs(getY() - t.getY()) && getY() > t.getY() )
goUp();
else if ( Math.abs(getX() - t.getX()) < Math.abs(getY() - t.getY()) && getY() < t.getY() )
goDown();
setX(getX() + dx);
setY(getY() + dy);
}
public void goUp() {
dx = 0;
dy = -1;
}
public void goDown() {
dx = 0;
dy = 1;
}
public void goLeft() {
dx = -1;
dy = 0;
}
public void goRight() {
dx = 1;
dy = 0;
}
最佳答案
下面的代码有些粗略,但是应该做您想要的。在您当前的代码中,敌人正在第一帧中沿X方向移动一个像素,然后在下一帧中沿Y方向移动一个像素,这使移动看起来像是对角线。下面的代码为敌方坦克设置了一个短期目标点,该目标点可以在X或Y方向上朝MOVE_BLOCK定义的一定距离前进。敌人将移动直到它越过该目标点,然后重新计算它应该朝哪个方向移动。请注意,每次创建新框架时都会调用敌人移动,因此大概每秒60次。
// The tank will move this distance in x or y before changing directions
private final int MOVE_BLOCK = 120;
// The short-term target of the enemy tank
Point target = null;
public void enemyMove(Tank t) {
/* true if enemy is moving left and enemy is already left of target point,
* or moving right and right of target... */
boolean passedTarget = target == null ||
(dx < 0 && getX() < target.getX()) ||
(dx > 0 && getX() > target.getX()) ||
(dy < 0 && getY() < target.getY()) ||
(dy > 0 && getY() > target.getY());
// Calculate a new target point if the old target was passed
if(passedTarget) {
int xDist = Math.abs(getX() - t.getX());
int yDist = Math.abs(getY() - t.getY());
if ( xDist > yDist ) {
// Cover the remaining distance when close to the target
int moveLength = xDist < MOVE_BLOCK ? xDist : MOVE_BLOCK;
if( getX() >= t.getX() )
goLeft();
target = new Point(getX() - moveLength, getY());
else
goRight();
target = new Point(getX() + moveLength, getY());
} else {
int moveLength = yDist < MOVE_BLOCK ? yDist : MOVE_BLOCK;
if ( getY() >= t.getY() ) {
goUp();
target = new Point(getX(), getY() - moveLength);
} else {
goDown();
target = new Point(getX(), getY() + moveLength);
}
}
}
setX(getX() + dx);
setY(getY() + dy);
}