Calculating a projectiles angle required to hit object taking into account height and base rotation
Hello guys
I am making a WWII fps with AI, maps are pretty big (4km) and so my IA cannot just fire straight on the player but needs to calculate the proper angle to which rotate the gun in order to hit its target.
I got it working on flat ground, and no rotation. But as soon as either my target and my AI are on different height + my AI is rotated (here my AI is a tank going down hill) the trajectory gets all f* up
I have tried a lot but I give up guys, could anyone here help me out with this?
Here is what I currently have as a result (My target is to the left of the little sun where the audio source is) :
And here is my code calculating the angle :
public static void CalculateThrowAngle(Vector3 from, Vector3 to, float speed, out float angle)
{
float xx = to.x - from.x;
float xz = to.z - from.z;
float x = Mathf.Sqrt(xx * xx + xz * xz);
float y = to.y - from.y;
float v = speed;
float g = Physics.gravity.y;
float sqrt = (v * v * v * v) - (g * (g * (x * x) + 2 * y * (v * v)));
// Not enough range
if (sqrt < 0)
{
angle = 0.0f;
return;
}
angle = Mathf.Atan(((v * v) + Mathf.Sqrt(sqrt)) / (g * x));
angle = (angle * 360) / (float)(2 * Math.PI); // Conversion from radian to degrees
angle = 90 + angle; // Idk why but thats needed
angle *= -1; // Unity negative is upward, positive is pointing downard
}
My trajectory calculation is working just fine, hits at the very spot every time it shoots so I'm sure its the angle that doesn't get right since on flat ground it works!
It currently returns -0.31 which is .. well weird. By manually tweaking the gun, I found out that the result gun's X rotation should be -3.8 in order to hit the target
Any ideas?
Your answer
