我有一个 2D 侧视射击游戏,我需要一些新的视角。我目前正在研究瞄准,并且它部分有效: Guzzle 速度已知,重力已知,并且到目标的 x,y 距离也已知。使用 SE 和维基百科上的各种来源,我提出了以下方法来计算弹丸速度的起始 vector :
public Vector2 calculateAim(Vector2 pos, Unit target) {
// Check if previous calculation can be recycled
if (target.equals(lastTarget))
return lastAim.cpy();
lastTarget = target;
double v = RifleBullet.projectileSpeed; // Muzzle velocity
double g = Settings.gravity.y; // Gravity, positive value
double x = offset.x; // x distance to target. Negative if towards left
double y = offset.y; // y distance to target. Negative if lower
double theta = Math.atan(((v * v) - Math.sqrt((v*v*v*v) - (g*(g*(x*x) + 2*y*(v*v))))) / (g * x));
Vector2 aim = new Vector2(-(float)Math.cos(theta), (float)Math.sin(theta));
aim.nor();
aim.scl((float)RifleBullet.projectileSpeed);
lastAim = aim.cpy();
return aim;
}
以上部分有效:最右边的人会正确瞄准。然而,站在左边的那个人总是向错误的方向射击。看起来 Y 分量是正确的,但 X 分量完全颠倒了。如果我在计算 theta 后添加这个:
if (side.contains("left"))
angleInRadians += Math.PI;
...它们都能正确射击,但从长远来看这是不可行的,因为战场上会有更多的单位,当我到达那个点时,它肯定会引起问题。
我相信问题的根源可能是 Math.atan()
函数,因为我没有任何检查来了解三角函数计算中的假设三角形的方向。
我应该如何改进我的方法,以便无论谁在左/右/上/下,它都能正常工作?
最佳答案
Tenfour04说的很有帮助。您可能想要使用 Math.atan2(y,x)
而不是 Math.atan(y/x)
请注意,您不是自己进行除法,而是将 y 和 x 作为单独的参数给出。这样 atan2 就知道 5/2 和 -5/-2 之间的区别。对于普通的 atan 来说,它们看起来都是 2.5
关于java - 重写,以便 Math.atan() 无论方向如何都可以工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38537020/