Projectile prediction to hit moving target

I am currently working on a projectile detections system. The target is moving with a velocity and I am trying to find out at what angle do I need to point the gun to hit the target.
I followed this to write the equation…

The Player is the target and the turret is the attacker.


const FRotator ABaseTurretActor::GetTurretHeadDirection(const FVector TurretLocation, const FVector PlayerLocation) const
{
	FVector PlayerVelocity = PlayerActor->CurrentVelocity;
	FVector RelativePlayerLocation = (PlayerLocation - TurretLocation);

        double a = FVector::DotProduct(PlayerVelocity,PlayerVelocity) - ProjectileSpeed*ProjectileSpeed;
	double b = 2 * FVector::DotProduct(RelativePlayerLocation, PlayerVelocity);
	double c = FVector::DotProduct(RelativePlayerLocation, RelativePlayerLocation);

	double t1 = (-b + FMath::Sqrt((b*b) - 4 * a*c)) / 2 * a;
	double t2 = (-b - FMath::Sqrt((b*b) - 4 * a*c)) / 2 * a;
        GEngine->AddOnScreenDebugMessage(-1, GetWorld()->DeltaTimeSeconds, FColor::Magenta, FString::SanitizeFloat(t1) + "  " + FString::SanitizeFloat(t2));
}

In here, the player is the target… And Turrent location is the location of the attacker.

This doesn’t seem to work. I have yet to find the velocity but the values of time(t1 and t2) are huge… Basically around 7-8 digits. So I don’t think it would work…

Am I using the correct formula?

A few things stick out in my head, particularly about these two lines:


double t1 = (-b + FMath::Sqrt((b*b) - 4 * a*c)) / 2 * a;
double t2 = (-b - FMath::Sqrt((b*b) - 4 * a*c)) / 2 * a;

First, 4 is an integer, 4.0f is a float, 4.0 is a double. You always want to make sure your constants are the correct type, otherwise you could potentially get some nasty conversions (all though the compiler hopefully grasps your intent properly - but that can be a risky proposition).

Second, I don’t really understand your implementation of the algorithm in the link you provided. Where are the 4 and 2 constants coming from? I see t[SUP]4[/SUP] and t[SUP]2[/SUP] but that’s about it and those would be t * t * t * t, and t * t as you have b[SUP]2[/SUP] setup.

I recently answered a similar question on the AnswerHub that uses one of Newton’s Kinetic Equations to solve for the initial velocity, maybe give that a shot and see if that works for you.

Ahh… I missed the 4 and 2 being used as integer some reason.

Well solving for t gives a quadratic equation something like this.

To solve it I use the formula


Actually I found a simpler and more efficient to do it. I thought it wouldn’t work but it actually did.


float Time = (PlayerLocation - TurretLocation).Size() / (ProjectileSpeed - PlayerVelocity.Size());

I thought if ProjectileSpeed was a vector property it would have worked. But Projectile speed being a scalar made it work if I converted the PlayerVelocity to scalar…
Anyone why?