I’m making a first-person game, and I want the player to look through a security camera to take a screenshot to use later. How can I swap the cameras? I tried doing it with a Set Active with New Active checked blueprint node, but it didn’t work.
Swapping cameras is not the tool for this. Set Active changes what the player sees, but you do not want to see through the security camera, you want an image from it. For that you want a Scene Capture Component 2D writing into a Render Target, and the player’s own camera never has to move.
Put a SceneCapture2D on the security camera actor, create a Render Target asset, and assign it to the capture’s Texture Target. From then on that render target holds whatever the capture sees, and you can show it on a widget, put it on a material, or read the pixels out and save them.
Four settings decide whether this works or looks wrong.
Capture Source: set it to Final Color (LDR). The scene colour options hand you an untonemapped buffer that looks nothing like the game. This is the one that catches people out.
Capture Every Frame and Capture On Movement: turn both off. Left on, you are rendering the scene a second time every frame for a shot you take once. Call Capture Scene when the player presses the button instead.
Hidden Actors: add the player pawn if it can get between the camera and what you are shooting.
For a still you keep rather than a live feed, call Capture Scene once and then read the render target. In Blueprint that is Export Render Target to write a file, or Read Render Target Pixel if you only need colours. In C++ it is GameThread_GetRenderTargetResource then ReadPixels, and with Final Color LDR you want the default read flags with no gamma conversion, since the image is already tone mapped and in gamma space.
Worth knowing before you scale it up: a scene capture is a full extra render of the scene. One on demand is cheap. Several running every frame is not.
I’m a little confused about this; could you show me an example or something? I’m trying to save an image of the scene to use for thumbnails, so I don’t need it to be permanent in the game. I just want a high-angle view. Nothing in the game will show this view.
Sure. Here is the whole thing as a small actor you can drop in. This is cut down from what I use for map thumbnails, and I went and ran it before posting rather than trusting my memory of the docs.
One thing up front, because it is what bit me when I tested it. A scene capture has its own eye adaptation, and a single cold CaptureScene gets read before that has converged, so the picture comes out far darker than what the player is looking at. I shot the same framing at midday both ways to be sure: the cold one looked like dusk, the warmed up one looked like the actual scene. That is why this is two steps and not one call.
ThumbnailCamera.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ThumbnailCamera.generated.h"
class USceneCaptureComponent2D;
class UTextureRenderTarget2D;
UCLASS()
class YOURPROJECT_API AThumbnailCamera : public AActor
{
GENERATED_BODY()
public:
AThumbnailCamera();
/** Starts the capture, waits WarmUpSeconds, then writes Saved/Thumbnails/<FileName>.png */
UFUNCTION(BlueprintCallable, Category = "Thumbnail")
void CaptureToPNG(const FString& FileName);
UPROPERTY(EditAnywhere, Category = "Thumbnail")
int32 Size = 512;
UPROPERTY(EditAnywhere, Category = "Thumbnail")
float FOV = 60.f;
/** How long the capture is left rendering so its auto exposure can settle. */
UPROPERTY(EditAnywhere, Category = "Thumbnail")
float WarmUpSeconds = 1.5f;
private:
void Finish(FString FileName);
UPROPERTY()
TObjectPtr<USceneCaptureComponent2D> Capture = nullptr;
UPROPERTY()
TObjectPtr<UTextureRenderTarget2D> RT = nullptr;
};
ThumbnailCamera.cpp
#include "ThumbnailCamera.h"
#include "Components/SceneCaptureComponent2D.h"
#include "Engine/TextureRenderTarget2D.h"
#include "Engine/World.h"
#include "GameFramework/PlayerController.h"
#include "GameFramework/Pawn.h"
#include "ImageUtils.h"
#include "Kismet/KismetRenderingLibrary.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
#include "TimerManager.h"
AThumbnailCamera::AThumbnailCamera()
{
PrimaryActorTick.bCanEverTick = false;
RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
}
void AThumbnailCamera::CaptureToPNG(const FString& FileName)
{
UWorld* World = GetWorld();
if (World == nullptr) return;
RT = UKismetRenderingLibrary::CreateRenderTarget2D(World, Size, Size, RTF_RGBA8);
if (RT == nullptr) return;
Capture = NewObject<USceneCaptureComponent2D>(this);
Capture->SetupAttachment(GetRootComponent());
Capture->RegisterComponent();
// Absolute, or this actor's own transform gets composed into the framing you just set.
Capture->SetAbsolute(true, true, true);
Capture->SetWorldLocationAndRotation(GetActorLocation(), GetActorRotation());
Capture->TextureTarget = RT;
Capture->FOVAngle = FOV;
Capture->ProjectionType = ECameraProjectionMode::Perspective;
Capture->CaptureSource = ESceneCaptureSource::SCS_FinalColorLDR;
// Rendering every frame on purpose. A single cold capture gets read before the component's
// own eye adaptation has converged, and the shot comes out far darker than the player's
// view. The component is destroyed the moment the picture is taken, so nothing keeps running.
Capture->bCaptureEveryFrame = true;
Capture->bAlwaysPersistRenderingState = true;
if (APlayerController* PC = World->GetFirstPlayerController())
{
if (APawn* Pawn = PC->GetPawn())
{
Capture->HiddenActors.Add(Pawn);
}
}
FTimerHandle Handle;
World->GetTimerManager().SetTimer(Handle,
FTimerDelegate::CreateWeakLambda(this, [this, FileName]() { Finish(FileName); }),
FMath::Max(WarmUpSeconds, 0.1f), false);
}
void AThumbnailCamera::Finish(FString FileName)
{
if (Capture == nullptr || RT == nullptr) return;
TArray<FColor> Pixels;
if (FTextureRenderTargetResource* Resource = RT->GameThread_GetRenderTargetResource())
{
// Default read flags. FinalColorLDR is already tone mapped and in gamma space, and
// converting it again washes the image out.
Resource->ReadPixels(Pixels);
}
Capture->DestroyComponent();
Capture = nullptr;
if (Pixels.Num() != Size * Size) return;
// FinalColorLDR leaves alpha at whatever the scene wrote, which can be 0. Encode that
// straight to PNG and you get a perfectly captured, completely transparent image.
for (FColor& Pixel : Pixels)
{
Pixel.A = 255;
}
TArray64<uint8> PNG;
FImageUtils::PNGCompressImageArray(Size, Size, TArrayView64<const FColor>(Pixels.GetData(), Pixels.Num()), PNG);
if (PNG.Num() == 0) return;
const FString Path = FPaths::ProjectSavedDir() / TEXT("Thumbnails") / (FileName + TEXT(".png"));
FFileHelper::SaveArrayToFile(PNG, *Path);
}
Where to put it, and how it actually works
The actor is the camera. Wherever you drag it and however you rotate it, that is the shot. The component renders the scene from that transform into the render target, and your player’s camera is never touched.
For a high angle over something, drop the actor above the middle of it and set the pitch to around -45 in the Details panel. -90 is straight down and reads flat, so most thumbnails look better between -40 and -70. After that it is height and FOV until the whole thing is in frame. The quickest way to aim it is to right click it in the World Outliner, choose Pilot, fly the viewport to the view you want, then stop piloting.
If you want it framed automatically rather than by hand, take the bounds of whatever you are shooting, aim at the centre of those bounds, and pull back by the bounds radius divided by the tangent of half your FOV, with a little padding:
const float Radius = FMath::Max((float)Bounds.GetExtent().Size(), 100.f);
const float Distance = (Radius * 1.1f) / FMath::Tan(FMath::DegreesToRadians(FOV * 0.5f));
const FVector Loc = Bounds.GetCenter() - Rot.Vector() * Distance;
That is what I use for player-built maps, since I cannot know in advance how big one is going to be.
Firing it from Blueprint
Place the actor in the level, then in whatever Blueprint takes the shot:
- Get a reference to it. If it is placed in the level you can drag it straight into the graph from the World Outliner. If you spawn it at runtime, keep the return value from Spawn Actor.
-
- Drag off that reference and call CaptureToPNG with a file name.
-
- The file lands in YourProject/Saved/Thumbnails/ about a second and a half later.
The capture sees the world exactly as it is at that moment, so hide anything you do not want in the picture first. HiddenActors on the component takes specific actors out, which is how the player pawn is kept out of shot above.
- The file lands in YourProject/Saved/Thumbnails/ about a second and a half later.
If you want to stay in Blueprint entirely
Same sequence as nodes. Create a Render Target asset, put a Scene Capture Component 2D on an actor, set Capture Source to Final Color (LDR), tick Capture Every Frame, wait a second or so with a Delay, then Export Render Target and destroy the actor. The alpha problem in the comment above does not bite you on that path, the exporter handles it.
One thing I tried that did not help, in case you go looking: pinning the exposure with AutoExposureMinBrightness and AutoExposureMaxBrightness on the capture’s post process settings made no difference in my test. Letting it render for a moment was what actually fixed the darkness.