JakeTee
(Jake Tee)
July 26, 2018, 9:59am
15
anonymous_user_18b10ba8:
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).
I know this is a very old thread. First of all thank you for this solution. However as stated below, the recoil kick is based on the frame rate. I did some research and in order to not depend on the frame rate, we have to multiply the recoil by DeltaTime after being interp. But what about the recoil recovery ? Since it is interp to recoil - which is already multiplied by DeltaTime. If we multiply this again it will be wrong. Thanks a lot