需要帮助破译Projectile Motion的公式

时间:2009-12-29 00:28:01

标签: artificial-intelligence physics game-physics

我需要实施一些AI来弄清楚如何用射弹运动击中目标。

我在维基百科发现了这个:

Angle required to hit coordinate

这看起来就像我需要的东西,特别是因为我有一个额外的问题从高于零高度发射射弹。但是,我的数学技能并不是很好,所以对我来说这一切看起来都是完全无稽之谈,我不知道如何将其中任何一个转换为代码。

如果有人可以将其分解为我能用基本操作符(+ - *%)和函数(sin,cos,sqrt等)理解的东西,我真的很感激。

2 个答案:

答案 0 :(得分:7)

如果xTarget/yTarget是目标的位置,xProj/yProj是弹丸的初始位置,v弹丸的初始速度(以米/秒为单位),那么公式就会转换为以下伪代码:

x = xTarget - xProj;
y = yTarget - yProj;
g = 9.8;

tmp = pow(v, 4) - g * (g * pow(x, 2) + 2 * y * pow(v, 2));

if tmp < 0
   // no solution
else if x == 0
   angle1 = pi/2;
   if y < 0
      angle2 = -pi/2;
   else
      angle2 = pi/2;
   end
else
   angle1 = atan((pow(v, 2) + sqrt(tmp)) / (g * x));
   angle2 = atan((pow(v, 2) - sqrt(tmp)) / (g * x));
end

g是重力常数(~9.8 m / s ^ 2),atan arcus tangent 函数,pow是幂函数。 if语句是必要的,因为公式没有解决方案(如果目标无法通过初始速度到达),一个解决方案(然后angle1 == angle2)或两个解决方案(如{{3}中所示)动画;这也是你在公式中加上+/-符号的原因。)

在大多数编程语言中,您还会找到atan2,在这种情况下,您应该能够用

替换一些代码
if tmp < 0
   // no solution
else
   angle1 = atan2(pow(v, 2) + sqrt(tmp), g * x);
   angle2 = atan2(pow(v, 2) - sqrt(tmp), g * x);
end

答案 1 :(得分:2)

公式很简单,不用担心推导。

x is the horizontal distance away of the target you're trying to hit
y is the vertical distance away of the target you're trying to hit
v is the initial velocity of the launch
g is the acceleration due to gravity (9.81 m/s on earth)

并且formula on that link将为您提供发射射弹所需的角度,以便在坐标(x,y)上击中目标