# Fixing the relativity of projectile firing

Hi!

Nice course section, I had lots of fun with it!
One thing that bothered me was the relativity of the projectile velocity (or more specificially that it didn’t conform to relativity); I set my projectile initial velocity quite low, and when driving forwards with the tank, I drove into the projectiles. In real life this wouldn’t happen, as the velocity of the tank would be added to the initial velocity of the projectile. So, I set it up to do just that!

First I made a function to get the current velocity of the `BasePawn` (`GetCurrentVelocity()`), and a protected variable to store it.
Then, in `Tank`, I calculate it in the `Tick` function;

``````	//Update current velocity
if(GetActorLocation() != previousFrameLocation) {
FVector deltaLocation = GetActorLocation() - previousFrameLocation;
currentVelocity = deltaLocation/DeltaTime;
previousFrameLocation = GetActorLocation();
} else {
currentVelocity = FVector::ZeroVector;
}
``````

where `previousFrameLocation` is an FVector holding the position the tank was in the last frame.
So, Now I have the velocity of the tank. Time to do some vector maths to calculate the velocity we should put on the projectile. We can use the dot product for this, and the function `SetVelocityInLocalSpace()` for the projectile movement component. I do this, in ABAsePawn::Fire():

``````auto projectileMovementComponent = Cast<UProjectileMovementComponent>(projectile->GetComponentByClass(UProjectileMovementComponent::StaticClass()));
projectileMovementComponent->SetVelocityInLocalSpace((projectileMovementComponent->InitialSpeed + GetCurrentVelocity().Dot(projectileSpawnPoint->GetForwardVector()))*FVector::UnitX())
``````

In other words, I add a calculated velocity to the InitialSpeed, and set that as the forward velocity of the projectile. In this way, the projectile (world) velocity takes the velocity of the tank into account. As an example, with an InitialVelocity of the projectile set to 1000, and driving the tank forwards with a velocity of 500, I will now get a projectile world velocity of 1500 if I shoot frowards, 1000 if I shoot to the sides, and 500 if I shoot backwards.

1 Like