I'm having an issue with calculating the predicted linear angle a projectile needs to move in to intersect a moving enemy ship for my 2D game.
I've tried following the document here, but what I've have come up with is simply awful.
protected Vector2 GetPredictedPosition(float angleToEnemy, ShipCompartment origin, ShipCompartment target)
{
// Below obviously won't compile (document wants a Vector, not sure how to get that from a single float?)
Vector2 velocity = target.Thrust - 25f; // Closing velocity (25 is example projectile velocity)
Vector2 distance = target.Position - origin.Position; // Range to close
double time = distance.Length() / velocity.Length(); // Time
// Garbage code, doesn't compile, this method is incorrect
return target.Position + (target.Thrust * time);
}
I would be grateful if the community can help point out how this is done correctly.
EDIT
Here is my (working) method following the advice given:
protected Vector2 GetPredictedPosition(ShipCompartment origin, ShipCompartment target, Ship enemyShip, Ship firingShip)
{
Vector2 targetVelocity = enemyShip.Direction * enemyShip.Thrust;
Vector2 projectileVelocity = firingShip.Direction * 25f;
Vector2 velocity = targetVelocity - projectileVelocity; // Closing velocity
Vector2 distance = target.Position - origin.Position; // Range to close
double time = distance.Length() / velocity.Length(); // Time
return target.Position + new Vector2(Convert.ToSingle(targetVelocity.X * time), Convert.ToSingle(targetVelocity.Y * time));
}