How to create recoil that's not instant?

I realize this is an old thread, however I was also looking to achieve a similar effect. I discovered a method which works quite nicely for me, hopefully it can help out someone else.

The following code assumes your custom character class is AMyCharacter and your custom player controller class is AMyPlayerController.

Add the following to MyCharacter.h:



float Recoil;            //Stores current negative (upwards pitch rotation) recoil
float RecoilRecovery;    //Stores current positive (downwards pitch rotation) recoil recovery


Override the Tick method within MyCharacter.cpp:



void AMyCharacter::Tick(float DeltaSeconds) {

    Super::Tick(DeltaSeconds);

    AMyPlayerController* MyPC = Cast<AMyPlayerController>(Controller);
    float ApplyPitch;

    Recoil = FMath::FInterpTo(Recoil, 0, DeltaSeconds, 10.0f);
    RecoilRecovery = FMath::FInterpTo(RecoilRecovery, -Recoil, DeltaSeconds, 20.0f);
    ApplyPitch = Recoil + RecoilRecovery;

    if (MyPC) {
        MyPC->AddPitchInput(ApplyPitch);
    }

}


The code should be pretty self explanatory. Simply decrement your character’s Recoil property to by a negative value to instigate the recoil kick (e.g. Recoil -= 0.5). Typically you would do this as soon as your weapon is fired. The view will return back to the original location (spring-like recoil). It works with fully automatic weapons. You can adjust the speed of both interpolations.

Note that this will only apply to the up/down rotation (pitch), however the exact same concept can be used for the left/right rotation (yaw).