首页 > 代码库 > Unreal Engine 4切换默认Camera实现

Unreal Engine 4切换默认Camera实现

默认的,UE4,会以AGameMode中设置DefaultPawnClass对象中摄影机作为默认摄影机。有时候我们想要一个全局的摄影机对场景进行观察,这就需要重新创建一个摄影机,并在这两个摄影机直接切换。下面看下如何实现。

在APlayerController类中,有一个SetViewTarget方法,参数是一个AActor指针,就是实现此功能的。因为参数必须是AActor,即必须是AActor中包含的Camera组件才有效,所有,先创建一个AActor对象。

FreeCameraActor.h

UCLASS()
class NANTOPDOWN_API AFreeCameraActor : public AActor
{
GENERATED_UCLASS_BODY()


public:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera)
TSubobjectPtr<class UCameraComponent> TopDownCameraComponent;


UFUNCTION(BlueprintCallable, Category = "View Target")
void ChangeViewTarget();


virtual void BeginPlay() override;

private:
AActor* OldActor;
};


ChangeViewTarget()方法提供给Blueprint调用,用于在Character的Camera和FreeCamera之间切换。


FreeCameraActor.cpp


AFreeCameraActor::AFreeCameraActor(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{
TopDownCameraComponent = PCIP.CreateDefaultSubobject<UCameraComponent>(this, TEXT("TopDownCamera"));
this->RootComponent = TopDownCameraComponent;
OldActor = NULL;
}


void AFreeCameraActor::ChangeViewTarget()
{
AActor* pActor = this->GetWorld()->GetFirstPlayerController()->GetViewTarget();
if (pActor != OldActor)
{
this->GetWorld()->GetFirstPlayerController()->SetViewTarget(OldActor);
}
else
{
this->GetWorld()->GetFirstPlayerController()->SetViewTarget(this);
}
}


void AFreeCameraActor::BeginPlay()
{
Super::BeginPlay();


OldActor = this->GetWorld()->GetFirstPlayerController()->GetViewTarget();


this->GetWorld()->GetFirstPlayerController()->SetViewTarget(this);
}


在Editor中创建一个从AFreeCameraActor继承的Actor,并拖放到场景中去。可以看到一个包含了摄影机的对象。然后编辑Level Blueprint,加入脚本代码



Play场景,按下1键,就能看到摄影机在character和刚才新建的摄影机间进行切换了。

Unreal Engine 4切换默认Camera实现