Search code examples
c++unreal-engine4

Camera Shake Not Activating Unreal C++


I am trying to set a camera shake for my character in Unreal C++.

Currently, I declare the instance variable in my header class.

Using log outputs, the code is reaching the right location in the OnFire() function, meaning none of the pointers are null. But the camera shake doesn't work.

UPROPERTY(EditAnywhere)
UCameraShake* CShake;

// And here is how I call it

void AZombieCharacter::BeginPlay(){
    SetUpCameraShake();
}


...

void AZombieCharacter::OnFire() {

...
    auto CTRLR = UGameplayStatics::GetPlayerController(GetWorld(), 0);

    if (CTRLR) {
        auto CM = CTRLR->PlayerCameraManager;
        if (CM) {
            CM->PlayCameraShake(CShake->GetClass(), 1.0f);
        }
        else {
            UE_LOG(LogTemp, Warning, TEXT("CANNOT FIND CM"));
        }
    }
    else {
        UE_LOG(LogTemp, Warning, TEXT("CANNOT FIND CTRLR"));
    }
}
...
void AZombieCharacter::SetUpCameraShake() {


    CShake = UCameraShake::StaticClass()->GetDefaultObject<UCameraShake>();

    CShake->OscillationDuration = 4.f;
    CShake->OscillationBlendInTime = 0.5f;
    CShake->OscillationBlendOutTime = 0.5f;

    CShake->RotOscillation.Pitch.Amplitude = FMath::RandRange(5.0f, 10.0f);
    CShake->RotOscillation.Pitch.Frequency = FMath::RandRange(25.0f, 35.0f);

    CShake->RotOscillation.Yaw.Amplitude = FMath::RandRange(5.0f, 10.0f);
    CShake->RotOscillation.Yaw.Frequency = FMath::RandRange(25.0f, 35.0f);
}

Thanks.


Solution

  • Play Camera Shake Accepts an UClass / TSubClassOf<UCameraShake> knowing that would expect us to think that this function would eventually construct a new object and ignore the default object options.

    I would recommend to subclass the UCameraShake class and use TSubClassOf to store your class type instead of the pointer like CShake. As it may be garbage collected without you knowing who knows?

    Here is a C++ tutorial on UCameraShake's. https://unrealcpp.com/camera-shake/

    The reason your shake is not playing is likely having no actual parameters passed to the shake. Only the default ones despite your try to set the default values, it does not seem to take it into account for newly created objects.