Hi,
I was getting annoyed by the fact that the turret could travel over 180 degrees if you moved between +90 and -90 degrees behind the tank. This is my workaround to fix that.
TankTurret.cpp
void UTankTurret::Rotate(float RelativeSpeed, FVector RelativeLocation)
{
RelativeSpeed = FMath::Clamp<float>(RelativeSpeed, -1, 1);
// Calculate how much we need to move the Turret this tick
float YawChange = RelativeSpeed * MaxRotationSpeed * GetWorld()->DeltaTimeSeconds;
float RawNewYaw;
// Make sure we take the short route
if(RelativeRotation.Yaw > 90 && RelativeLocation.Y < 0)
{
YawChange = FMath::Abs(YawChange);
}
if (RelativeRotation.Yaw < -90 && RelativeLocation.Y > 0)
{
YawChange = -YawChange;
}
// The final value of Yaw with the movement for this tick.
RawNewYaw = RelativeRotation.Yaw + YawChange;
// Do it
SetRelativeRotation(FRotator(0, RawNewYaw, 0));
}
TankAimComponent.cpp
void UTankAimingComponent::MoveTurret(FVector Direction)
{
FRotator NewDirection = Direction.Rotation() - Barrel->GetForwardVector().Rotation();
Turret->Rotate(NewDirection.Yaw, Direction);
}
It’s not 100% perfect, but it is far less annoying (for me atleast) than what it used to do. Any suggestions on improvements would be greatly appreciated, math is not my strong point.