Limiting Pitch Rotation on Object

Hello, I am currently working with the Flying Code template and am tweaking the pre-existing code and adding in new functionalities.

I’m trying to limit the pitch rotation on the UFO object so that I can’t fly upside down. I want to limit the rotation so that it can only rotate up to a certain angle. I’m guessing that it has something to do with getting the object’s LocalRotation in the Tick function, but I’m new to both UE4 and C++ (I come from a Unity C# background), so I’m unfamiliar with the syntax.

1 Like

The AMyFlyingProjectPawn::Tick function updates the actor’s rotation by applying a delta rotation via the AddActorLocalRotation function. Since it only deals with a delta, to limit the pawn’s total pitch you need to get the current rotation and clamp the delta such that the new pitch is within the range you want. The below is one way you could do it.

MyFlyingProjectPawn.h

(Added within class declaration)

UPROPERTY(Category=Movement, EditAnywhere, BlueprintReadWrite)
float MaxPitch;

UPROPERTY(Category=Movement, EditAnywhere, BlueprintReadWrite)
float MinPitch;

MyFlyingProjectPawn.cpp

(Added within constructor)

MaxPitch = 30.f;
MinPitch = -30.f;

(Replacing related lines in Tick function)

const float OldPitch = GetActorRotation().Pitch;
const float MinDeltaPitch = MinPitch - OldPitch;
const float MaxDeltaPitch = MaxPitch - OldPitch;

// Calculate change in rotation this frame
FRotator DeltaRotation(0,0,0);
DeltaRotation.Pitch = FMath::ClampAngle(CurrentPitchSpeed * DeltaSeconds, MinDeltaPitch, MaxDeltaPitch);
DeltaRotation.Yaw = CurrentYawSpeed * DeltaSeconds;
DeltaRotation.Roll = CurrentRollSpeed * DeltaSeconds;

// Rotate plane
AddActorLocalRotation(DeltaRotation);

Code-wise you could do it similarly for roll and yaw, I assume. There might be an issue with potential to introduce gimbal lock or something similar where you get quirky behavior. I’m not an expert in quarternion math, so maybe someone else knows.

Works perfectly thank you! I’m assuming it works the exact same way for roll and yaw as well

I’m not to familiar with programming and would like to do this, what would the blueprint for this look like? Or should I post a separate question.