How to set camera in C++

Making a top-down game that only needs an othrographic camera in the sky to look directly down onto the scene for each level. The camera never needs to move. This is easy with blueprint:

Get Player Control, Event BeginPlay, CameraActor and Set view target with blend.

How to do this in c++ though? I’m trying to learn about the c++ side of UE4. TY.

You can find a complete example here No need to recreate all the code, but you have an example to set a camera in C++. You can also look at the Top Down example game in the editor (create a new project, under “C++ Feature”).

Short answer :

Create a APawn object and set it to the DefaultPawnClass in your game mode

In the constructor of the APawn class you can create the camera



RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
USpringArmComponent* armComponent = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraSpringArm"));
armComponent->SetupAttachment(RootComponent);
armComponent->SetRelativeLocationAndRotation(FVector(0.0f, 0.0f, 30.0f), FRotator(-50.0f, 0.0f, 0.0f));
armComponent->TargetArmLength = 400.0f;
armComponent->bEnableCameraLag = true;
armComponent->CameraLagSpeed = 6.0f;
armComponent->bDrawDebugLagMarkers = true;

m_cameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraMain"));
m_cameraComponent->SetupAttachment(armComponent, USpringArmComponent::SocketName);

The camera will spawn and look at the Player Start.

I just copy/paste a code I done in a project, I think you don’t need the USpringArmComponent if your camera isn’t move.

2 Likes