UE4 C++学习 摄像机切换

1. 创建一个 Camera 和 一个 Cube ,Cube 增加一个 Camera组件,勾选 Constrain Aspect Ratio

2. 新建一个c++类 Actor ,命名为CameraDirector 

CameraDirector.h

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "CameraDirector.generated.h"

UCLASS()
class QUICKSTARTCODE_API ACameraDirector : public AActor
{
	GENERATED_BODY()
	
public:	
	// Sets default values for this actor's properties
	ACameraDirector();
    
    UPROPERTY(EditAnywhere)
    AActor* CameraOne;
    
    UPROPERTY(EditAnywhere)
    AActor* CameraTwo;
    
    float TimeToNextCameraChange;

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

};

CameraDirector.cpp

// Fill out your copyright notice in the Description page of Project Settings.


#include "CameraDirector.h"
#include "Kismet/GameplayStatics.h"

// Sets default values
ACameraDirector::ACameraDirector()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

}

// Called when the game starts or when spawned
void ACameraDirector::BeginPlay()
{
	Super::BeginPlay();
	
}

// Called every frame
void ACameraDirector::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
    const float TimeBetweenCameraChanges = 2.0f;
    const float SmoothBlendTime = 0.75f;
    TimeToNextCameraChange -= DeltaTime;
    if(TimeToNextCameraChange <= 0.0f){

        TimeToNextCameraChange += TimeBetweenCameraChanges;
        // Find the actor that handles control for the local player
        APlayerController* OurPlayerController = UGameplayStatics::GetPlayerController(this,0);
        if(OurPlayerController){
            if ((OurPlayerController->GetViewTarget() != CameraOne)&&(CameraOne!=nullptr)) {
                OurPlayerController->SetViewTarget(CameraOne);
            }else if((OurPlayerController->GetViewTarget()!= CameraTwo)&&(CameraTwo!=nullptr)){
                OurPlayerController->SetViewTargetWithBlend(CameraTwo,SmoothBlendTime);
            }
        }
        }
}

效果如图所示:

 

参考链接如下:

https://docs.unrealengine.com/en-US/Programming/Tutorials/AutoCamera/index.html 

你可能感兴趣的:(UE4)