Unfortunately I don't have access to a compiler and I need to see if I've derived the correct equation for projectile leading. This assumes I need to find out the time as well as the direction of the shot given Spos(shot initial position - a vector), Sspeed(speed of the shot - float), Tpos(target initial position), Tvel(velocity vector for target or speed + direction). I guess where I'm fuzzy is where I invert the quadratic equation because technically u = 1/t. Here is what I have done.
We need to use two equations:
(I)Spos + tSdir = Tpos + tTvel
(II)Sdirdot(Sdir) = Sspeed^2
Divide (I) by t solve for Sdir:
Spos/t + V = Tpos/t + Tvel
Sdir = (Tpos – Spos)/t + Tvel = Du + Tvel where D = Tpos – Spos and u = 1/t
using equation (II):
Sspeed^2 = Sdirdot(Sdir) = (Ddot(D))u^2 + 2u(Ddot(Tvel)) + Tveldot(Tvel)
u^2(Ddot(D)) + 2u(Ddot(Tvel)) + Tveldot(Tvel) - Sspeed^2 = 0
using quadratic equation: A = Ddot(D) B = 2Ddot(Tvel) C = Tveldot(Tvel) - Sspeed^2
u = (-2Ddot(Tvel) + sqrt((2Ddot(Tvel))^2 – 4(Ddot(D))(Tveldot(Tvel) - Sspeed^2)) / 2Ddot(d)
so t = the inverse of the above equation // should I be inverting here?
And Sdir = (Tpos – Spos) / t + Tvel
Finally in code:
CODE
Vector LeadTarget(Vector Spos, float Sspeed, Vector Tpos, Vector Tvel)
{
Vector D = Tpos - Spos;
float A = D.dot(D);
float B = 2 * D.dot(Tvel);
float C = Tvel.dot(Tvel) - Sspeed * Sspeed;
float t = (A * 2) / (-B + sqrt(B * B + 4 * A * C)); // this is where I invert but am unsure if I should.
return (D/t + Tvel).Normal();
}