I want to implement a new recoil system in the ShooterGame template, and so I want to rotate the player’s first-person weapon relative to a rotator. If the rotator is 15° right and 15° upwards, then the gun should be pointed 15° right and upwards from where the player is looking. I have not been able to do this because once the gun rotates 15°, the 15° pitch increase happens from a new pivot facing that new yaw. I have no idea how to calculate a rotator that corrects for this change. I have tried adding the rotator in different places in the OnCameraUpdate function, but nothing gets me the desired result. Can anyone help me? This is probably really simple, but I am a novice coder and I have become so frustrated at this roadblock.
The gun should be in the same location on each of these pictures (15° up and to the right): Straight - Up - Down
Here is the OnCameraUpdate code, which determines the location and rotation of the weapon. The capital THIS is where I added 15.0f for those above photos; they’re not in the original code.
void AShooterCharacter::OnCameraUpdate(const FVector& CameraLocation, const FRotator& CameraRotation)
{
USkeletalMeshComponent* DefMesh1P = Cast<USkeletalMeshComponent>(GetClass()->GetDefaultSubobjectByName(TEXT("PawnMesh1P")));
const FMatrix DefMeshLS = FRotationTranslationMatrix(DefMesh1P->RelativeRotation, DefMesh1P->RelativeLocation);
const FMatrix LocalToWorld = ActorToWorld().ToMatrixWithScale();
// Mesh rotating code expect uniform scale in LocalToWorld matrix
const FRotator RotCameraPitch(CameraRotation.Pitch + TEST, 0.0f, 0.0f);
const FRotator RotCameraYaw(0.0f, CameraRotation.Yaw + TEST, 0.0f);
const FMatrix LeveledCameraLS = FRotationTranslationMatrix(RotCameraYaw, CameraLocation) * LocalToWorld.Inverse();
const FMatrix PitchedCameraLS = FRotationMatrix(RotCameraPitch) * LeveledCameraLS;
const FMatrix MeshRelativeToCamera = DefMeshLS * LeveledCameraLS.Inverse();
const FMatrix PitchedMesh = MeshRelativeToCamera * PitchedCameraLS;
Mesh1P->SetRelativeLocationAndRotation(PitchedMesh.GetOrigin(), PitchedMesh.Rotator());
}