Ok, I''m not sure if this is possible, but is there a way to find a firing angle for a gun if you are given the initial velocity from the gun, initial position of the gun, and an exact distance to a target? Assume the gun and target are on a level plane. I know there could be multiple "correct" angles, but I want the one with the smallest "time to target". Thanks.
If you only know the position of the gun and its distance form the target, but you do not know the position of the target then you do not have enough information to solve this problem. This would mean you only know that the target is somewhere on circle, around the gun. You can’t hit a target if you do not know where it is.
If you do know the position of the target and the both the target and gun are stationary, then the solution would be:
Gun is at: (Gx, Gy) and Target is at: (Tx, Ty) then:
Angle from the horizontal axis = arctan ((Ty-Gy)/(Tx-Gx))
Note: If you use the Win32 function: atan() to calculate the arctan, remember the results are in radians not degrees. If you want to derive this equation just look at the properties of trigonometric functions.
If either the target or the gun is moving, this solution will not work. Let me know if you want the solution for moving objects.
This is easy if you add both the angle and time to your calculations. E.g.
time = t angle = a speed = v gravity = g
Horizontal motion: x = vt cos (a) Vertical motion: y = vt sin (a) - 0.5 * g * t * t
It hits the ground when y = 0, so
y = vt sin (a) - 0.5 * g * t * t = 0
Solving this quadratic gives this happens when t = 0 and t = 2v sin (a) / g
The first value is when it is fired, so it hits when
t = 2v sin (a) / g
putting this into the x equation gives
x = 2v*v sin (a) cos (a) / g
x = v*v sin (2a) / g
sin (2a) = (g * x) / (v * v)
if (g * x) / (v * v) < 1 this has two solutions, one less than 45 degrees and one greater than 45 degrees. The one with smallest time t is the smallest angle, i.e. the one less than 45 degrees,which then is: