So I have created spaceship shooter game where ships have turrets on them . Now I want those turrets to shoot a moving target meaning I want the projectile to intercept and hit the target that is headed in some direction. Every projectile has its own speed which is constant. Also the ship which has the turret is also moving at a constant speed.
So far I have made this:
Vector2 toTarget = targetShip.GlobalPosition - Player.currentShip.GlobalPosition;
Vector2 targetVel = ( targetShip.dir.Normalized() * targetShip.speed * delta) - (Player.currentShip.dir.Normalized() * Player.currentShip.speed * delta);
float distance = toTarget.Length();
float a = targetVel.Dot(targetVel) - (projectile.speed * projectile.speed);
float b = 2 * targetVel.Dot(toTarget);
float c = -distance * distance; //toTarget.Dot(toTarget);
float p = -b / (2 * a);
float q = Mathf.Sqrt((b * b) - 4 * a * c) / (2 * a);
float t1 = p - q;
float t2 = p + q;
if (t1 < 0 && t2 < 0)
{
return;
}
float timeToInterception = 1;
if (t1 > 0 && t2 > 0)
timeToInterception = Mathf.Min(t1, t2);
//else
//timeToInterception = Mathf.Max(t1, t2);
Vector2 aimSpot = targetShip.GlobalPosition + targetVel * timeToInterception;
dir = aimSpot - GlobalPosition;
GlobalRotation = Mathf.LerpAngle(GlobalRotation, dir.Angle(), turnRate * delta);
The Global Rotation is where the turret will look at and it shoots from its barrel. The method kinda works and sometimes does not work(the projectiles shoot behind the moving target). Vector2 targetVel = ( targetShip.dir.Normalized() * targetShip.speed * delta) - (Player.currentShip.dir.Normalized() * Player.currentShip.speed * delta);
that part is me calculating velocities I am not sure if its correct...
I commented out the else
part because the turrets just disappear from my ship if I let that be there and I am also uneducated why.
I've read THIS answer from this forum but I don't understand it especially his edit part. In his edit part I don't understand where to plug that projectile velocity. Also why is my turret disappearing when I uncomment else
in my code?
If someone can give me some explanation I would be very thankful!