Okay, this all takes place in a nice and simple 2D world... :)
Suppose I have a static object A at position Apos, and a linearly moving object B at Bpos with bVelocity, and an ammo round with velocity Avelocity...
How would I find out the angle that A has to shoot, to hit B, taking into account B's linear velocity and the speed of A's ammo ?
Right now the aim's at the current position of the object, which means that by the time my projectile gets there the unit has moved on to safer positions :)
Following is polar coordinate based aiming code in C++.
To use with rectangular coordinates you would need to first convert the targets relative coordinate to angle/distance, and the targets x/y velocity to angle/speed.
The "speed" input is the speed of the projectile. The units of the speed and targetSpeed are irrelevent, as only the ratio of the speeds are used in the calculation. The output is the angle the projectile should be fired at and the distance to the collision point.
The algorithm is from source code available at http://www.turtlewar.org/ .
I wrote an aiming subroutine for xtank a while back. I'll try to lay out how I did it.
Disclaimer: I may have made one or more silly mistakes anywhere in here; I'm just trying to reconstruct the reasoning with my rusty math skills. However, I'll cut to the chase first, since this is a programming Q&A instead of a math class :-)
How to do it
It boils down to solving a quadratic equation of the form:
Note that by
sqr
I mean square, as opposed to square root. Use the following values:Now we can look at the discriminant to determine if we have a possible solution.
If the discriminant is less than 0, forget about hitting your target -- your projectile can never get there in time. Otherwise, look at two candidate solutions:
Note that if
disc == 0
thent1
andt2
are equal.If there are no other considerations such as intervening obstacles, simply choose the smaller positive value. (Negative t values would require firing backward in time to use!)
Substitute the chosen
t
value back into the target's position equations to get the coordinates of the leading point you should be aiming at:Derivation
At time T, the projectile must be a (Euclidean) distance from the cannon equal to the elapsed time multiplied by the projectile speed. This gives an equation for a circle, parametric in elapsed time.
Similarly, at time T, the target has moved along its vector by time multiplied by its velocity:
The projectile can hit the target when its distance from the cannon matches the projectile's distance.
Wonderful! Substituting the expressions for target.X and target.Y gives
Substituting the other side of the equation gives this:
... subtracting
sqr(t * projectile_speed)
from both sides and flipping it around:... now resolve the results of squaring the subexpressions ...
... and group similar terms ...
... then combine them ...
... giving a standard quadratic equation in t. Finding the positive real zeros of this equation gives the (zero, one, or two) possible hit locations, which can be done with the quadratic formula:
First rotate the axes so that AB is vertical (by doing a rotation)
Now, split the velocity vector of B into the x and y components (say Bx and By). You can use this to calculate the x and y components of the vector you need to shoot at.
You need
Vx = Bx
andSqrt(Vx*Vx + Vy*Vy) = Velocity of Ammo
.This should give you the vector you need in the new system. Transform back to old system and you are done (by doing a rotation in the other direction).
Jeffrey Hantin has a nice solution for this problem, though his derivation is overly complicated. Here's a cleaner way of deriving it with some of the resultant code at the bottom.
I'll be using x.y to represent vector dot product, and if a vector quantity is squared, it means I am dotting it with itself.
We know that the position of the projectile and target with respect to
t
time can be described with some equations.We want these to be equal to each other at some point (the point of intersection), so let's set them equal to each other and solve for the free variable,
projvel
.Let's forget about the notion of origin and target position/velocity. Instead, let's work in relative terms since motion of one thing is relative to another. In this case, what we now have is
relpos = targetpos - originpos
andrelvel = targetvel - originvel
We don't know what
projvel
is, but we do know that we wantprojvel.projvel
to be equal tospeed^2
, so we'll square both sides and we getWe can now see that the only free variable is time,
t
, and then we'll uset
to solve forprojvel
. We'll solve fort
with the quadratic formula. First separate it out intoa
,b
andc
, then solve for the roots.Before solving, though, remember that we want the best solution where
t
is smallest, but we need to make sure thatt
is not negative (you can't hit something in the past)Now, if we have a
t
value, we can plugt
back into the original equation and solve for theprojvel
Now, to the shoot the projectile, the resultant global position and velocity for the projectile is
And you're done!
My implementation of my solution in Lua, where vec*vec represents vector dot product:
Here's an example where I devised and implemented a solution to the problem of predictive targeting using a recursive algorithm: http://www.newarteest.com/flash/targeting.html
I'll have to try out some of the other solutions presented because it seems more efficient to calculate it in one step, but the solution I came up with was to estimate the target position and feed that result back into the algorithm to make a new more accurate estimate, repeating several times.
For the first estimate I "fire" at the target's current position and then use trigonometry to determine where the target will be when the shot reaches the position fired at. Then in the next iteration I "fire" at that new position and determine where the target will be this time. After about 4 repeats I get within a pixel of accuracy.