UE4 C++学习笔记之初识Pawn类

Pawn是一种由真实玩家或AI控制的 Actor

任务1:创建一个C++ Pawn类,并给其添加静态网格组件和摄像头组件
Creature.h代码如下:

#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "Creature.generated.h"

UCLASS()
class LEARNTEST_API ACreature : public APawn
{
	GENERATED_BODY()

public:
	// Sets default values for this pawn's properties
	ACreature();

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

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

	// Called to bind functionality to input(和Actor类相比多了玩家控制组件)
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;

        //新增静态网格体组件
	UPROPERTY(EditAnywhere)
	class UStaticMeshComponent* StaticMesh;  //此处进行前向声明,这样在这里就不需要include相关的头文件了,减少编译时间且降低编译出错概率
        
        //新增摄像头组件
	UPROPERTY(EditAnywhere)
	class UCameraComponent* Camera;
};

可以看出引擎自动生成的代码部分,Pawn类较Actor类多了玩家控制组件。

此外,为了实现在游戏中玩家的可视化,我们还需要自己添加静态网格组件和摄像头组件。

Creature.cpp代码构造函数如下:

ACreature::ACreature()
{
 	// Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;
        //初始化根结点组件、静态网格组件、摄像头组件,并将静态网格组件和摄像头组件依附于根结点上
	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
	StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh"));
	StaticMesh->SetupAttachment(GetRootComponent());
	Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent"));
	Camera->SetupAttachment(GetRootComponent());
        //初始化摄像头组件的相对位置和方向
	Camera->SetRelativeLocation(FVector(-300, 0, 300));
	Camera->SetRelativeRotation(FRotator(-45, 0, 0));
}

任务2:将场景中的Pawn设置为默认Pawn类

步骤一、由C++ Pawn类生成蓝图类Pawn类BP_Creature,设置静态网格体组件并将其拖入场景中

步骤二、新建GameMode蓝图类BP_LearnGameMode,将Default Pawn类设置为步骤一创建的BP_Creature

步骤三、在项目设置中应用当前蓝图类BP_GameMode

步骤四、对场景中的Pawn类进行设置,选择自动控制玩家0

这样运行游戏时,便将默认Pawn切换为我们放置在场景中的BP_Creature了。(运行模式设置为选中的窗口)

猜你喜欢

转载自blog.csdn.net/weixin_44928892/article/details/107944790