我试图让球员旋转并面对一个目标位置,并且遇到了一个我无法修复的问题。
当船向目标位置旋转时,当它到达目标位置的正下方时,它会发疯,在向下(远离目标位置)时左右移动,最后离开屏幕。
我不想限制屏幕,因为它会看起来奇怪,当它是缓慢旋转,如果它是接近屏幕限制。在这种情况下,如果我确实限制了屏幕,它仍然会被卡在底部,因为它不断地左转和右转。我上传了一张图片,试图更好地解释我的问题。
黄色是指船舶正在运动的方向(它向目标位置旋转,但会越过红线),绿色是一个向目标位置的虚向量,红色是另一个虚拟矢量,它代表着每当船疯狂时。当绿线出现在红线上方时,船就开始飞出屏幕。
public void ai() {
switch (playerArrived()) {
case 0:
break;
case 1:
pTargetPos.set(ran(0, Gdx.graphics.getWidth()), ran(0, Gdx.graphics.getHeight()));
System.out.println("Player Destination Reached: " + pPos.x + "," + pPos.y + " Moving to new point: " + pTargetPos.x + "," + pTargetPos.y);
break;
}
turn();
move();
ePlayerBody.set(pPos.x, pPos.y, pWidth);
}
public int playerArrived() {
if (pTargetPos.x < pPos.x + pWidth && pTargetPos.x > pPos.x - pWidth && pTargetPos.y < pPos.y + pHeight && pTargetPos.y > pPos.y - pHeight) {
return 1;
} else {
return 0;
}
}
public float ran(float low, float high) {
return (float) (Math.random() * (high - low + 1)) + low;
}
public void move() {
pVel.set(pTargetPos.x - pPos.x, pTargetPos.y - pPos.y);
pVel.nor();
pVel.x *= sMaxSpeed + Gdx.graphics.getDeltaTime();
pVel.y *= sMaxSpeed + Gdx.graphics.getDeltaTime();
pVel.setAngle(pNewRotation + 90);
pPos.add(pVel);
}
public void turn() {
pRotation = ((Math.atan2(pTargetPos.x - pPos.x, -(pTargetPos.y - pPos.y)) * 180.0d / Math.PI)+180.0f);
pNewRotation += (pRotation - pNewRotation) * Gdx.graphics.getDeltaTime();
System.out.println(pRotation+" "+pNewRotation);
}
我上传了一张图片,试图更好地解释我的问题。
发布于 2015-07-01 13:19:11
当你的船在目标的正下方,而在目标的左边,调用Math.atan2(pTargetPos.x - pPos.x, -(pTargetPos.y - pPos.y))
会返回一个非常接近π/2的值。当你的船正好在目标的下方,而在目标的右边,这个呼叫会返回-π/2。当你越过红线时,你的方向会翻转180度(π半径)。这就是为什么“快疯了”。
你需要找出一个更好的方法来决定你应该转向哪一个角度。我会对此提出建议,但我仍然不清楚你到底在期待什么行为。
发布于 2015-07-01 15:45:04
这对我起了作用:
public void turn() {
pRotation = ((tPos.y - pPos.y) / (tPos.x - pPos.x) * 180.0d / Math.PI);
pNewRotation += (pRotation - pNewRotation) * Gdx.graphics.getDeltaTime();
}
public void move() {
pVel.set(pDir);
pVel.nor();
pVel.x *= sMaxSpeed + Gdx.graphics.getDeltaTime();
pVel.y *= sMaxSpeed + Gdx.graphics.getDeltaTime();
pVel.setAngle(pNewRotation + 90);
pPos.add(pVel);
}
https://stackoverflow.com/questions/31161928
复制相似问题