我正在坦克上实施旋转加农炮。 NPC的大炮跟随玩家坦克(自动旋转)。
我正在计算:
Math.min
和Math.abs
使用Google)问题在于从0度到360度或从360度到0度的跳跃使得大炮“松散”#34;玩家坦克和大炮四处旋转。
现在就这样做了:
Vector2 Tank2Enemy = tank.getPosition().sub(closestEnemyTank.getPosition());
float angleTank2Enemy = Tank2Enemy.angleRad(); // this is the angle of the vector tank -> enemy in radians
float angleCannon = tank.cannon.getOwnAngle(); // this is the cannon-angle in radians
float diffAngle = Math.min(Math.abs(angleCannon - angleTank2Enemy), MathUtils.PI - Math.abs(angleCannon - angleTank2Enemy));
if (diffAngle > 0.01f || diffAngle < -0.01f) { // dead zone
if (diffAngle > 0.01f) {
direction = -1; // this goes to cannon.getBody().setAngularVelocity(cannonAngularVelocity);
}
else if (diffAngle < 0.01f) {
direction = 1; // this goes to cannon.getBody().setAngularVelocity(cannonAngularVelocity);
}
}
return direction;
答案 0 :(得分:1)
一个好的做法是让角度始终为正,例如为了不混淆不同的角度。您可以注意到角度270将以与-90度相同的方式工作。您可以通过附加一个简单的检查来解决您的问题:
while(angle >= 2*Math.PI) //angle in radians
angle -= 2*Math.PI;
while(angle < 0)
angle += 2*Math.PI;
更新: 我想问题在于你计算diffAngle的方式。你可以试试以下吗?
float diffAngle = angleCannon - angleTank2Enemy; // or angleTank2Enemy - angleCannon, depending on the direction of angles in your game
double sign = Math.signum(diffAngle);
float diffAngle = sign >= 0 ? Math.min(diffAngle, 2*MathUtils.PI - diffAngle) : Math.max(diffAngle, -(2*MathUtils.PI - diffAngle));
答案 1 :(得分:0)
好吧我这样解决了:
if (angleTank2Enemy > angleCannon) {
diffAngle = angleTank2Enemy - angleCannon;
if (diffAngle > MathUtils.PI) {
rotDirRight = true;
}
else rotDirRight = false;
}
else {
diffAngle = angleCannon - angleTank2Enemy;
if (diffAngle > MathUtils.PI) {
rotDirRight = false;
}
else rotDirRight = true;
}
if ((diffAngle) > 0.05f) { // dead zone
if (rotDirRight) direction = 1; // this goes to cannon.getBody().setAngularVelocity(cannonAngularVelocity);
else direction = -1; // this goes to cannon.getBody().setAngularVelocity(cannonAngularVelocity);
}
return direction;