最简单的 UE 4 C++ 教程 —— 平滑切换玩家的相机(视图目标)到 Actor 位置【十三】

本教程介绍如何在UE4中实现玩家视图目标的平滑切换。通过创建C++Actor子类SetViewTargetBlend,并在BeginPlay函数中设置视图目标为指定Actor,实现2秒内的平滑过渡。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原教程是基于 UE 4.18,我是基于 UE 4.25】

英文原地址

接上一节教程,在这个简单的教程中,我们将在游戏开始时,简单地平滑混合运动来改变玩家的视图目标。

创建一个新的 C++ Actor 子类并将其命名为 SetViewTargetBlend 。在头文件中,我们将声明一个 actor 变量,并将其称为 MyActor  并使新角色在任何地方都可编辑。

SetViewTargetBlend.h

#pragma once

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

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

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

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

	// declare variables
	UPROPERTY(EditAnywhere)
	AActor* MyActor;
	
};

首先,为了拥有玩家,我们需要 #include Kismet/GameplayStatics.h 文件。

#include "SetViewTarget.h"
// include gameplay statics header file
#include "Kismet/GameplayStatics.h"

在这个例子中,我们所有的逻辑都放在了 BeginPlay 函数中【不是构造函数中哦,不然 UE4 可能会崩溃】。我们需要通过执行UGameplayStatics::GetPlayerController(this, 0) 来拥有当前玩家。这将获得游戏场景中的第一个玩家。

接下来,我们将使用 SetViewTargetWithBlend(MyActor, 2.f) 将我们拥有的玩家的视图目标设置为 MyActor 变量。我们将混合时间设置为 2 秒,这将指示相机移动到新目标所需要的时间。

下面是最后的 .cpp 文件。

SetViewTargetBlend.cpp

#include "SetViewTargetBlend.h"
// include gameplay statics header file
#include "Kismet/GameplayStatics.h"


// Sets default values
ASetViewTargetBlend::ASetViewTargetBlend()
{
 	// 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 ASetViewTargetBlend::BeginPlay()
{
	Super::BeginPlay();

	//Find the actor that handles control for the local player.
	APlayerController* OurPlayerController = UGameplayStatics::GetPlayerController(this, 0);
	
	//Smoothly transition to our actor on begin play.
	OurPlayerController->SetViewTargetWithBlend(MyActor, 2.f);
	
}

// Called every frame
void ASetViewTargetBlend::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

编译代码。将新角色拖放到游戏中。在编辑器中,向 actor 的细节面板中的 MyActor 变量添加一个静态网格。

按下播放键,玩家的摄像机将在 2 秒内移到新角色身上。

效果如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值