Original Post
Here''s the situation:
2 ships flying in free space (ship A and ship B). They have velocities Va and Vb and positions Ra and Rb. Ship A wants to fire at ship B so that, assuming ship B maintains constant velocity, the bullet will hit ship B. You know the eject velocity of the bullet. Also (I didn''t program this game), the bullet does not inherit the velocity of the ship that fires it.
So, you can form 2 lines:
Rs(t) = Ra0 + Vs * t = Ra0 + (|Vs|cos(theta)i + |Vs|sin(theta)j) * t
Rb(t) = Rb0 + Vb * t
...where:
Rs = position of bullet
Ra0 = initial position of ship A
Vs = velocity of shot
Rb = position of ship B
Rb0 = initial position of ship B
Vb = velocity of ship B
t = time
The 2 unknowns are theta and t. So to solve you set Rb = Rs, and you can get 2 equations (x and y direction) with 2 unknowns and solve.
I came up with a solution, but it is pretty complicated and involved using the quadratic formula. Can you see a simpler solution?
Here''s my solution:
theta = arcsin[ (Ry + Vby * t) / (|Vs| * t) )
(everything with a y subscript is the y component)
t = {-Vb * R +- sqrt[(Vb * R)^2 - (|Vb|^2 - |Vs|^2) * |R|^2]} / (|Vb|^2 - |Vs|^2)
where R = Rb0 - Ra0
Solve for t and plug into theta.
I tested my solution with a few test cases and it worked, but I''m afraid of the sqrt and the arcsin and their effect on performance. Is there a better way?