【UE4笔记】C++游戏控制的摄像机

目录

  • 自主操作题目
  • 逻辑
  • 代码

本文尝试编写了官方文档游戏控制的摄像机中的自主操作题目2

自主操作题目

使用一个数组变量来存储摄像机,而不是摄像机1(CameraOne)和摄像机2(CameraTwo),这样你就可以遍历任意数量摄像机的序列,而不是仅仅两个。

逻辑

  1. 头文件创建一个EditAnywhere的Camera数组(TArray)(设置成UPROPERTY以便于在虚幻编辑器中绑定具体的摄像机)
  2. 头文件设置平滑转换两个摄像机的时间间隔SmoothBlendTime(这里将其设置成了UPROPERTY以便于在虚幻编辑器中修改)
  3. cpp的tick函数中设置在每个摄像机停留的时间TimeBetweenCameraChange
  4. TimeToNextCameraChange减去Deltatime后判断其是否小于零,是则触发摄像机转换
  • 在摄像机转换中:
    • 重设 TimeToNextCameraChange
    • 获取本地玩家控制的Actor(UGameplayStatics::GetPlayerController)
    • 编写摄像机之间的转换
      • 确认当前正在使用的摄像机并查看下一个摄像机是否存在
      • 存在则进行摄像机的转换(OurPlayerController->SetViewTargetWithBlend函数)

代码

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

#pragma once

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

UCLASS()
class QUICKSTART_API ACameraDirector : public AActor
{
	GENERATED_BODY()
	
public:	
	// Sets default values for this actor's properties
	ACameraDirector();

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

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

	UPROPERTY(EditAnywhere)
	TArray<AActor*> CameraArr;

	float TimeToNextCameraChange;

	UPROPERTY(EditAnywhere)
		float SmoothBlendTime = 0.75f;

};
// Fill out your copyrightnotice in the Description page of Project Settings.
//CameraDirector.cpp

#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 TimeBetweenCameraChange = 2.0f;
	TimeToNextCameraChange -= DeltaTime;

	if (TimeToNextCameraChange <= 0.0f) {
		TimeToNextCameraChange += TimeBetweenCameraChange;

		//查找处理本地玩家控制的Actor。
		APlayerController* OurPlayerController = UGameplayStatics::GetPlayerController(this, 0);
		bool bUnchanged = true;

		if (OurPlayerController) {
			if (CameraArr[0] && (OurPlayerController->GetViewTarget() == CameraArr[CameraArr.Num() - 1])) {
				OurPlayerController->SetViewTargetWithBlend(CameraArr[0], SmoothBlendTime);
			}
			else {
				for (int32 Index = 0; bUnchanged && Index != CameraArr.Num() - 1; ++Index) {
					if (CameraArr[Index + 1] && (OurPlayerController->GetViewTarget() == CameraArr[Index])) {
						OurPlayerController->SetViewTargetWithBlend(CameraArr[Index + 1], SmoothBlendTime);
						bUnchanged = false;
					}
				}
			}
		}
	}

}

你可能感兴趣的:(UE4学习手册,ue4)