虚幻C++基础 day1

虚幻C++概念

虚幻C++类的继承结构

  • 虚幻引擎C++类层级结构(Hierarchy)
    在这里插入图片描述
  • 这些基本类又派生出了很多子类,例:
    在这里插入图片描述

UE中的反射与垃圾回收系统

  • 例如一个创建了一个Actor类,有一个Actor类型指针去指向这个Actor类,如果的指针被销毁了,那么这个Actor类UE系统会判断为垃圾,参与了反射与垃圾回收系统后,UE会在适当的时机销毁这个Actor
  • 使用宏进行标识,UE的UHT系统会帮我们进行垃圾回收
    在这里插入图片描述

创建第一个UObject子类

  • 新建一个基于Object的子类
    在这里插入图片描述在这里插入图片描述
  • 这里是灰色的,是因为没有指定反射角色
    在这里插入图片描述
  • 我们可以将这个类指定一下给蓝图
    在这里插入图片描述
    在这里插入图片描述

创建UObject的蓝图类与基础宏参数

  • 将MyObject创建类图类
    在这里插入图片描述
    在这里插入图片描述
  • 因为是最开始的基类,不能显示,所以没有可视化的脚本编辑框
    在这里插入图片描述
  • 设置变量与函数到蓝图中
    在这里插入图片描述
    在这里插入图片描述
  • 运行结果,写的数据就可以到UE的蓝图类中进行使用
    在这里插入图片描述

使用UE_LOG打印日志与在蓝图中实例化继承于Object的类

  • UPROPERTY(BlueprintReadWrite, Category = “My Variables”),中的Category是分类的意思,可以在蓝图调用的时候去显现出来会将你的东西挂载到这个分类下面。
  • MyObject.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "MyObject.generated.h"

/**
 * 
 */
UCLASS(Blueprintable)
class CPROJECT_API UMyObject : public UObject
{
	GENERATED_BODY()
public:
	//构造函数
	UMyObject();

	UPROPERTY(BlueprintReadWrite, Category = "My Variables")//声明变量可以蓝图系统中进行读写
	//变量
	float xiaogua;
	
	UFUNCTION(BlueprintCallable, Category = "My Functions")//声明函数可以在蓝图中进行调用
		//函数成员
	void myFunction();
};

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


#include "MyObject.h"

UMyObject::UMyObject()
{
	xiaogua = 0.0f;
}

void UMyObject::myFunction()
{
	//第一个变量是输出类型,第二个变量是输出级别,第三个输出内容
	//LogTemp临时类型,Log,Warning,Error输出级别
	UE_LOG(LogTemp,Log,TEXT("Hello,World"));
	UE_LOG(LogTemp, Warning, TEXT("Hello,World"));
	UE_LOG(LogTemp, Error, TEXT("Hello,World"));
}

在这里插入图片描述
在这里插入图片描述

  • Object类是不能放入到场景中的,我们需要在UE的关卡蓝图中去实例化,使用Construct Object from Class蓝图专门用来实例化继承Object类的,还可以将实例化的对象提升出来
    在这里插入图片描述
  • 运行后,就可以看见输出内容了
    在这里插入图片描述

删除自定义C++类

  • 蓝图部分中直接删除保存即可
  • 找到项目路径中的source下的项目名里面的自己写的类删除,其他类不要动
    在这里插入图片描述
  • 然后删除这个文件
    在这里插入图片描述
  • 最后重新生成一下这个项目文件
    在这里插入图片描述
  • 因为删除了一些文件,直接点是重建即可
    在这里插入图片描述

Actor类与相关API

创建自己的Actor子类

UE中的前缀

  • 派生自Actor的类带有A前缀,如AController
  • 派生自Object的类带有U前缀,如UComponent
  • Enums的前缀是E,如EFortificationType
  • Interface的前缀是I,如IAbilitySystemInterface
  • Template前缀是T,如TArray
  • 派生自SWidget类的(Slate UI)带有前缀S,如SButton
  • 其他类前缀为F,如FVector
  • MyActor.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

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

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

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

};
  • MyActor.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyActor.h"

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

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

}
  • AActor基类有写入Blueprintable所以不需要在UCLASS里面写入,也可以直接创建蓝图实例化
    在这里插入图片描述

组件简介与使用蓝图类扩展代码的优点

  • 当创建好Actor默认类后生成蓝图,蓝图会自动给这个类设置个根组件进行辨识,可以添加自己的组件将其覆盖,只需要将组件拖拽到组件上,如果要回复默认组件,就将自己的组件删除即可
    在这里插入图片描述
  • 可以给予一些网格体与材质
    在这里插入图片描述
  • 就可以在世界里面显示
    在这里插入图片描述

在C++中创建静态网格组件

  • UPROPERTY(VisibleAnyWhere,Category = " MyStatic")
    • VisibleAnyWhere:设置可见属性为全部可见
    • Category:种类
      UStaticMeshComponent:创建一个静态网格体
	//设置组件属性与种类
	UPROPERTY(VisibleAnyWhere, Category = "MyStatic")
	//定义一个静态组件
	UStaticMeshComponent* MyStatic;
  • MyStatic = CreateDefaultSubobject<UStaticMeshComponent>(TEXT(“MyStatic”));
    • CreateDefaultSubobject:这是一个模版函数,返回创建的这个子对象
      在这里插入图片描述
  • MyActor.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

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

	//设置组件属性与种类
	UPROPERTY(VisibleAnyWhere, Category = "MyStatic")
	//定义一个静态组件
	UStaticMeshComponent* MyStatic;

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

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

};
  • MyActor.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyActor.h"

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

	//创建默认根组件,如果报错,因为设置了文本,报错会提示MyStatic错误
	MyStatic = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStatic"));
}

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

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

}
  • 运行结果
    在这里插入图片描述
    在这里插入图片描述

控制Actor位置与宏参数介绍

EditInstanceOnly宏参数与Actor移动函数

  • UPROPERTY(EditInstanceOnly, Category = “MyActorProperties | Vector”)
    • EditInstanceOnly:只运行在实例上进行编辑
    • Category = “MyActorProperties | Vector”:MyActorProperties 下的子文件夹Vector
	UPROPERTY(EditInstanceOnly, Category = "MyActorProperties | Vector")
	//新建一个三维空间向量变量
	FVector InitLocation;
  • InitLocation = FVector(0.0f);:构造赋初值,构造方法很多,一般常用如下两种
    在这里插入图片描述
  • SetActorLocation:将Actor传送到新位置
  • MyActor.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

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

	//设置组件属性与种类
	UPROPERTY(VisibleAnyWhere, Category = "MyStatic")
	//定义一个静态组件
	UStaticMeshComponent* MyStatic;

	UPROPERTY(EditInstanceOnly, Category = "MyActorProperties | Vector")
	//新建一个三维空间向量变量
	FVector InitLocation;

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

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

};
  • MyActor.pp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyActor.h"

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

	//创建默认根组件,如果报错,因为设置了文本,报错会提示MyStatic错误
	MyStatic = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStatic"));

	//构造赋初值
	InitLocation = FVector(0.0f);
}

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

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

}
  • 运行结果,每次运行,Actor就会移动到默认(0,0,0)坐标位,因为设置了实例化编辑,可以在场景实例中更改FVector坐标位
    在这里插入图片描述

VisibleInstanceOnly与EditDefaultsOnly

  • UPROPERTY(VisibleInstanceOnly,Category = “MyActorProperties | Vector”)
    • VisibleInstanceOnly:只运行在示例上进行显示
    • Category = “MyActorProperties | Vector”:MyActorProperties 下的子文件夹Vector
	UPROPERTY(VisibleInstanceOnly, Category = "MyActorProperties | Vector")
	//新建一个三维空间向量变量,用来记录上一次位置
	FVector PlacedLocation;
  • UPROPERTY(EditDefaultsOnly,Category = “MyActorProperties | Vector”)
    • EditDefaultsOnly:只能在蓝图模版中进行编辑
    • Category = “MyActorProperties | Vector”:MyActorProperties 下的子文件夹
  • 虚幻中的bool变量,前必须加上b进行标识
UPROPERTY(EditDefaultsOnly,Category = "MyActorProperties | Vector")
	//虚幻的bool变量前必须加上b,程序会默认去掉的,但是必须定义时必须要有
	bool bGotoInitLocation;
  • MyActor.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

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

	//设置组件属性与种类
	UPROPERTY(VisibleAnyWhere, Category = "MyStatic")
	//定义一个静态组件
	UStaticMeshComponent* MyStatic;

	UPROPERTY(EditInstanceOnly, Category = "MyActorProperties | Vector")
	//新建一个三维空间向量变量
	FVector InitLocation;

	UPROPERTY(VisibleInstanceOnly,Category = "MyActorProperties | Vector")
	//新建一个三维空间向量变量,用来记录上一次
	FVector PlacedLocation;

	UPROPERTY(EditDefaultsOnly,Category = "MyActorProperties | Vector")
	//虚幻的bool变量前必须加上b,程序会默认去掉的,但是必须定义时必须要有
	bool bGotoInitLocation;
protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

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

};
  • MyActor.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyActor.h"

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

	//创建默认根组件,如果报错,因为设置了文本,报错会提示MyStatic错误
	MyStatic = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStatic"));

	//构造赋初值
	InitLocation = FVector(0.0f);
	PlacedLocation = FVector(0.0f);
	bGotoInitLocation = false;
}

// Called when the game starts or when spawned
void AMyActor::BeginPlay()
{
	Super::BeginPlay();
	//获取位置
	PlacedLocation = GetActorLocation();
	
	if (bGotoInitLocation)
	{
		SetActorLocation(InitLocation);
	}
	
}

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

}
  • 运行结果,当这勾选时,场景中所有的此Actor都会设置到InitLocation位置
    在这里插入图片描述
    在这里插入图片描述

VisibleDefaultOnly与EditAnyWhere

  • UPROPERTY(VisibleDefaultsOnly, Category= “MyActorProperties | Vector”)
    • VisibleDefaultsOnly:只在蓝图模版中显示
  • UPROPERTY(EditAnywhere, Category = “MyActorProperties | Vector”)
    • EditAnywhere:设置编辑属性为全部能编辑
UPROPERTY(VisibleDefaultOnly,Category="MyActorProperties | Vector")
FVector WordOrigin;
UPROPERTY(EditAnywhere, Category = "MyActorProperties | Vector")
FVector LocationOffset;
  • MyActor.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

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

	//设置组件属性与种类
	UPROPERTY(VisibleAnyWhere, Category = "MyStatic")
	//定义一个静态组件
	UStaticMeshComponent* MyStatic;

	UPROPERTY(EditInstanceOnly, Category = "MyActorProperties | Vector")
	//新建一个三维空间向量变量
	FVector InitLocation;

	UPROPERTY(VisibleInstanceOnly,Category = "MyActorProperties | Vector")
	//新建一个三维空间向量变量,用来记录上一次
	FVector PlacedLocation;

	UPROPERTY(EditDefaultsOnly,Category = "MyActorProperties | Vector") 
	//虚幻的bool变量前必须加上b,程序会默认去掉的,但是必须定义时必须要有
	bool bGotoInitLocation;

	UPROPERTY(VisibleDefaultsOnly, Category = "MyActorProperties | Vector")
	FVector WordOrigin;

	UPROPERTY(EditAnywhere, Category = "MyActorProperties | Vector")
	FVector LocationOffset;

	UPROPERTY(EditAnywhere, Category = "MyActorProperties | Vector")
	FVector TickLocationOffset;

	UPROPERTY(EditAnywhere, Category = "MyActorProperties | Vector")
	bool bShouldMove;
protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;
};
  • MyActor.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyActor.h"

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

	//创建默认根组件,如果报错,因为设置了文本,报错会提示MyStatic错误
	MyStatic = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStatic"));

	//构造赋初值
	InitLocation = FVector(0.0f);
	PlacedLocation = FVector(0.0f);
	bGotoInitLocation = false;
	WordOrigin = FVector(0.0f);
	TickLocationOffset = FVector(0.0f);
	bShouldMove = false;
}

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

	//获取位置
	PlacedLocation = GetActorLocation();

	if (bGotoInitLocation)
	{
		SetActorLocation(InitLocation);
	}
}

// Called every frame
void AMyActor::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	if (bShouldMove)
	{
		AddActorLocalOffset(TickLocationOffset);
	}
}
  • 运行结果,运行后Actor实例会沿x的-1方向不断移动
    在这里插入图片描述
    在这里插入图片描述

限定编辑中输入值的范围

  • 一般在组件的指针不会设置为EditAnywhere,因为这样会导致基于这个组件对象的所有派生的类都会被这个指针去指向,就会导致很多麻烦的问题

  • UPROPERTY(EditAnywhere, Category = “MyActorProperties | Vector”, meta= (ClampMin = -10, ClampMax = 10, UIMin = -10, UIMax = 10))

    • meta=(ClampMin= -10,ClampMax= 10, UIMin= -10, UIMax= 10)):clamp:键盘输入值控制,ui:鼠标拉动值控制
  • 运行结果,此时的TickLocationOffset的最大最小范围被设置
    在这里插入图片描述

给静态网格添加力与力矩

  • 静态网格开启物理模拟,加上简单碰撞,为了方便测试,以下是开启物理模拟未开启重力

  • MyStatic->AddForce(InitForce, “NAME_None”, bIsForce);

    • Force:Force vector to apply. Magnitude indicates strength of force.
    • BoneName:If a SkeletalMeshComponent, name of body to apply force to. ‘None’ indicates root body.
    • bAccelChange:If true, Force is taken as a change in acceleration instead of a physical force (i.e. mass will have no effect).
      在这里插入图片描述
  • MyStatic->AddTorque(InitTorque, “NAME_None”, bIsForce);

    • Torque:Torque to apply. Direction is axis of rotation and magnitude is strength of torque.
    • BoneName: If a SkeletalMeshComponent, name of body to apply torque to. ‘None’ indicates root body.
    • bAccelChange:If true, Torque is taken as a change in angular acceleration instead of a physical torque (i.e. mass will have no effect).
      在这里插入图片描述
//添加增加力
MyStatic->AddForce(InitForce, "NAME_None", bIsForce);
//添加上力矩
MyStatic->AddTorque(InitTorque, "NAME_None", bIsForce);
  • MyActor.h
	//力
	UPROPERTY(EditAnywhere, Category = "MyActorProperties | Physics")
	FVector InitForce;
	//力矩
	UPROPERTY(EditAnywhere, Category = "MyActorProperties | Physics")
	FVector InitTorque;
	//是否开启力 
	UPROPERTY(EditAnywhere, Category = "MyActorProperties | Physics")
	bool bIsForce;
  • MyActor.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyActor.h"

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

	//创建默认根组件,如果报错,因为设置了文本,报错会提示MyStatic错误
	MyStatic = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStatic"));

	//构造赋初值
	InitLocation = FVector(0.0f);
	PlacedLocation = FVector(0.0f);
	bGotoInitLocation = false;
	WordOrigin = FVector(0.0f);
	TickLocationOffset = FVector(0.0f);
	bShouldMove = false;

	InitForce = FVector(0.0f);
	InitTorque = FVector(0.0f);
	bIsForce = false;
}

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

	//获取位置
	PlacedLocation = GetActorLocation();

	if (bGotoInitLocation)
	{
		SetActorLocation(InitLocation);
	}
	
	//添加增加力
	MyStatic->AddForce(InitForce, "NAME_None", bIsForce);
	//添加上力矩
	MyStatic->AddTorque(InitTorque, "NAME_None", bIsForce);	
}

// Called every frame
void AMyActor::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	if (bShouldMove)
	{
		AddActorLocalOffset(TickLocationOffset);
	}
	
}
  • 运行结果
    请添加图片描述

使用sweep扫描碰撞与显示第一次扫描碰撞到的点

  • 扫描标志用于限制行动,例如:当sweep为真时,它会帮你扫描碰撞到的第一个实例然后停止行动
  • FHitResult会检测到第一次扫描到碰撞的点的位置
    在这里插入图片描述
// Called every frame
void AMyActor::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	if (bShouldMove)
	{
		FHitResult HitReslut;
		AddActorLocalOffset(TickLocationOffset, true, &HitReslut);
		UE_LOG(LogTemp, Warning, TEXT("X %f,Y %f,Z %f", HitReslut.Location.X, HitReslut.Location.Y, HitReslut.Location.Z));
	}	
}
  • 运行结果
    在这里插入图片描述

Pawn类与相关API

创建自己的Pawn子类

  • Pawn中有声明好的RootComponent变量提供使用,直接指定即可
  • SetupAttachment:将根组件附加到上面
  • GetRootComponent:返回该角色根组件
//此RootComponent是Pawn类声明好的,直接指定即可
RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));

//将根组件附加搭配静态网格上
MyStaticMesh->SetupAttachment(GetRootComponent());
  • MyPawn.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

UCLASS()
class CPROJECT_API AMyPawn : public APawn
{
	GENERATED_BODY()

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


	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	UStaticMeshComponent* MyStaticMesh;

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
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;

};
  • MyPawn.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyPawn.h"

// Sets default values
AMyPawn::AMyPawn()
{
 	// 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是Pawn类声明好的,直接指定即可
	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
	MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));

	//将根组件附加搭配静态网格上
	MyStaticMesh->SetupAttachment(GetRootComponent());
}

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

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

}

// Called to bind functionality to input
void AMyPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

}
  • 运行结果
    在这里插入图片描述

为Pawn类添加相机组件

  • SetRelativeLocation:设置相对位置
  • SetRelativeRotation:设置相对旋转
  • #include "Camera/CameraComponent.h":Camera的头文件
  • MyPawn.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

UCLASS()
class CPROJECT_API AMyPawn : public APawn
{
	GENERATED_BODY()

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


	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	UStaticMeshComponent* MyStaticMesh;
	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	//用class进行一下标明,遵循UE语法
	class UCameraComponent* MyCamera;

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
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;

};
  • MyPawn.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyPawn.h"
#include "Camera/CameraComponent.h"

// Sets default values
AMyPawn::AMyPawn()
{
 	// 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是Pawn类声明好的,直接指定即可
	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
	MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));

	//将根组件附加搭配静态网格上
	MyStaticMesh->SetupAttachment(GetRootComponent());

	MyCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("MyCamera"));
	MyCamera->SetupAttachment(GetRootComponent());
	//设置组件与根组件为相对位置
	MyCamera->SetRelativeLocation(FVector(-300.0f, 0.0f, 300.0f));
	MyCamera->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f));
}

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

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

}

// Called to bind functionality to input
void AMyPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

}
  • 运行结果
    在这里插入图片描述

设置GameMode

  • 创建一个Mode的蓝图
    在这里插入图片描述
  • 将默认Pawn类换成自己的
    在这里插入图片描述
  • 游戏模式换成自己的
    在这里插入图片描述
  • 设置控制玩家
    • AutoPossessPlayer= EAutoReceiveInput::Player0;
      在这里插入图片描述
//决定哪个PlayerController(如果有的话)应该在关卡开始或生成小兵时自动拥有该小兵
AutoPossessPlayer = EAutoReceiveInput::Player0;
  • MyPawn.cpp
AMyPawn::AMyPawn()
{
 	// 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是Pawn类声明好的,直接指定即可
	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
	MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));

	//将根组件附加搭配静态网格上
	MyStaticMesh->SetupAttachment(GetRootComponent());

	MyCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("MyCamera"));
	MyCamera->SetupAttachment(GetRootComponent());
	//设置组件与根组件为相对位置
	MyCamera->SetRelativeLocation(FVector(-300.0f, 0.0f, 300.0f));
	MyCamera->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f));

	//决定哪个PlayerController(如果有的话)应该在关卡开始或生成小兵时自动拥有该小兵
	AutoPossessPlayer = EAutoReceiveInput::Player0;
}
  • 运行结果,点击运行后,PlayerStart就会是BP_MyPawn的位置
    在这里插入图片描述
    在这里插入图片描述

按键映射与轴事件绑定

  • 设置轴按键映射
    在这里插入图片描述

  • 然后去Pawn类中添加两个处理移动的函数进行绑定

  • 头文件 #include “Components/InputComponent.h”

    • PlayerInputComponent->BindAxis(TEXT(“MoveForward”),this,&MoveForward);
    • BindAxis:Binds a delegate function an Axis defined in the project settings.Returned reference is only guaranteed to be valid until another axis is bound.
  • MyPawn.h中声明两个移动函数

private:
	//创建两个移动函数,进行绑定
	void MoveForward(float Value);
	void MoveRight(float Value);
  • MyPawn.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyPawn.h"
#include "Camera/CameraComponent.h"
#include "Components/InputComponent.h"

// Sets default values
AMyPawn::AMyPawn()
{
 	// 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是Pawn类声明好的,直接指定即可
	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
	MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));

	//将根组件附加搭配静态网格上
	MyStaticMesh->SetupAttachment(GetRootComponent());

	MyCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("MyCamera"));
	MyCamera->SetupAttachment(GetRootComponent());
	//设置组件与根组件为相对位置
	MyCamera->SetRelativeLocation(FVector(-300.0f, 0.0f, 300.0f));
	MyCamera->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f));

	//决定哪个PlayerController(如果有的话)应该在关卡开始或生成小兵时自动拥有该小兵
	AutoPossessPlayer = EAutoReceiveInput::Player0;
}

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

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

}

// Called to bind functionality to input
void AMyPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	//绑定移动函数
	PlayerInputComponent->BindAxis(TEXT("MoveForward"),this, &AMyPawn::MoveForward);
	PlayerInputComponent->BindAxis(TEXT("MoveRight"),this,&AMyPawn::MoveRight);
}

void AMyPawn::MoveForward(float Value)
{
}

void AMyPawn::MoveRight(float Value)
{
}

移动Pawn

  • 新建两个变量,一个速度一个是控制Pawn坐标位
  • 调用Tick中的DeltaTime进行移动,可以避免高设备的激进,DeltaTime会将高帧与底帧控制到一个速度点
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

UCLASS()
class CPROJECT_API AMyPawn : public APawn
{
	GENERATED_BODY()

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


	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	UStaticMeshComponent* MyStaticMesh;
	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	//用class进行一下标明,遵循UE语法
	class UCameraComponent* MyCamera;

	UPROPERTY(EditAnywhere, Category = "My Pawn Movement")
	float MaxSpeed;

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
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;


private:
	//创建两个移动函数,进行绑定
	void MoveForward(float Value);
	void MoveRight(float Value);
	FVector Velocity;
};
  • MyPawn.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyPawn.h"
#include "Camera/CameraComponent.h"
#include "Components/InputComponent.h"

// Sets default values
AMyPawn::AMyPawn()
{
 	// 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是Pawn类声明好的,直接指定即可
	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
	MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));

	//将根组件附加搭配静态网格上
	MyStaticMesh->SetupAttachment(GetRootComponent());
	//RootComponent->SetMobility(EComponentMobility::Type::Movable);

	MyCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("MyCamera"));
	MyCamera->SetupAttachment(GetRootComponent());
	//设置组件与根组件为相对位置
	MyCamera->SetRelativeLocation(FVector(-300.0f, 0.0f, 300.0f));
	MyCamera->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f));

	//决定哪个PlayerController(如果有的话)应该在关卡开始或生成小兵时自动拥有该小兵
	AutoPossessPlayer = EAutoReceiveInput::Player0;

	MaxSpeed = 100.0f;
	//等效于Velocity = FVector(0.0f,0.0f,0.0f);
	Velocity = FVector::ZeroVector;
}

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

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

	AddActorLocalOffset(Velocity * DeltaTime, true);
}

// Called to bind functionality to input
void AMyPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	//绑定移动函数
	PlayerInputComponent->BindAxis(TEXT("MoveForward"),this, &AMyPawn::MoveForward);
	PlayerInputComponent->BindAxis(TEXT("MoveRight"),this,&AMyPawn::MoveRight);

}

void AMyPawn::MoveForward(float Value)
{
	//FMath::Clamp(x,min,max)进行夹值
	Velocity.X = FMath::Clamp(Value, -1.0f, 1.0f) * MaxSpeed;
	
}

void AMyPawn::MoveRight(float Value)
{
	Velocity.Y = FMath::Clamp(Value, -1.0f, 1.0f) * MaxSpeed;
}
  • 运行结果,小球可以移动了
    在这里插入图片描述

添加SpringArm组件

  • SpringArmComponent是常用的相机辅助组件,主要作用是快速实现第三人称视角,相机避障,相机视角等功能
  • 头文件:#include “GameFramework/SpringArmComponent.h”
  • MyPawn.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

UCLASS()
class CPROJECT_API AMyPawn : public APawn
{
	GENERATED_BODY()

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

	//用class进行一下标明,遵循UE语法
	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class UStaticMeshComponent* MyStaticMesh;

	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class UCameraComponent* MyCamera;

	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class USpringArmComponent* MySpringArm;


	UPROPERTY(EditAnywhere, Category = "My Pawn Movement")
	float MaxSpeed;

	
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
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;


private:
	//创建两个移动函数,进行绑定
	void MoveForward(float Value);
	void MoveRight(float Value);
	FVector Velocity;
};
  • MyPawn.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyPawn.h"
#include "Camera/CameraComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/SpringArmComponent.h"


// Sets default values
AMyPawn::AMyPawn()
{
 	// 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是Pawn类声明好的,直接指定即可
	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
	MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));
	//将根组件附加搭配静态网格上
	MyStaticMesh->SetupAttachment(GetRootComponent());

	MySpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("MySpringArm"));
	MySpringArm->SetupAttachment(MyStaticMesh);
	MySpringArm->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f));//设置相对旋转
	MySpringArm->TargetArmLength = 400.0f;//无碰撞时弹簧臂的自然长度
	MySpringArm->bEnableCameraLag = true;//If true, camera lags behind target position to smooth its movement
	//如果bEnableCameraLag为真,则控制相机到达目标位置的速度。低值较慢(更多延迟),高值较快(更少延迟),而零是即时的(没有延迟)。
	MySpringArm->CameraLagSpeed = 3.0f; 

	MyCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("MyCamera"));
	//将摄像机附着到MySpringArm上
	MyCamera->SetupAttachment(MySpringArm);


	//决定哪个PlayerController(如果有的话)应该在关卡开始或生成小兵时自动拥有该小兵
	AutoPossessPlayer = EAutoReceiveInput::Player0;

	MaxSpeed = 100.0f;
	//等效于Velocity = FVector(0.0f,0.0f,0.0f);
	Velocity = FVector::ZeroVector;
}

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

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

	AddActorLocalOffset(Velocity * DeltaTime, true);
}

// Called to bind functionality to input
void AMyPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	//绑定移动函数
	PlayerInputComponent->BindAxis(TEXT("MoveForward"),this, &AMyPawn::MoveForward);
	PlayerInputComponent->BindAxis(TEXT("MoveRight"),this,&AMyPawn::MoveRight);

}

void AMyPawn::MoveForward(float Value)
{
	//FMath::Clamp(x,min,max)进行夹值
	Velocity.X = FMath::Clamp(Value, -1.0f, 1.0f) * MaxSpeed;
	
}

void AMyPawn::MoveRight(float Value)
{
	Velocity.Y = FMath::Clamp(Value, -1.0f, 1.0f) * MaxSpeed;
}
  • 运行结果
    在这里插入图片描述

设置默认材质

  • 头文件:#include “UObject/ConstructorHelpers.h”
  • 选择引擎材质的引用路径:
    在这里插入图片描述
//添加默认材质与默认材质球
	static ConstructorHelpers::FObjectFinder<UStaticMesh> StaticMeshAsset(TEXT("StaticMesh'/Engine/BasicShapes/Sphere.Sphere'"));
	static ConstructorHelpers::FObjectFinder<UMaterialInterface> MaterialAsset(TEXT("Material'/Engine/EditorMaterials/PersonaFloorMat.PersonaFloorMat'"));
	if (StaticMeshAsset.Succeeded() && MaterialAsset.Succeeded())//判断是否加载成功
	{
		//设置默认材质与材质球
		MyStaticMesh->SetStaticMesh(StaticMeshAsset.Object);
		MyStaticMesh->SetMaterial(0, MaterialAsset.Object);
		MyStaticMesh->SetWorldScale3D(FVector(0.5f));//设置默认缩放
	}
  • MyPawn.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

UCLASS()
class CPROJECT_API AMyPawn : public APawn
{
	GENERATED_BODY()

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

	//用class进行一下标明,遵循UE语法
	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class UStaticMeshComponent* MyStaticMesh;

	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class UCameraComponent* MyCamera;

	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class USpringArmComponent* MySpringArm;

	UPROPERTY(EditAnywhere, Category = "My Pawn Movement")
	float MaxSpeed;

	//接口
	FORCEINLINE UStaticMeshComponent* GetStaticMeshComponent() { return MyStaticMesh; }
	FORCEINLINE USpringArmComponent* GetSpringArmComponent() { return MySpringArm; }
	
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
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;


private:
	//创建两个移动函数,进行绑定
	void MoveForward(float Value);
	void MoveRight(float Value);
	FVector Velocity;
};
    • MyPawn.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyPawn.h"
#include "Camera/CameraComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "UObject/ConstructorHelpers.h"

// Sets default values
AMyPawn::AMyPawn()
{
 	// 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是Pawn类声明好的,直接指定即可
	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));

	MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));
	MyStaticMesh->SetupAttachment(GetRootComponent());//将根组件附加搭配静态网格上

	//添加默认材质与默认材质球
	static ConstructorHelpers::FObjectFinder<UStaticMesh> StaticMeshAsset(TEXT("StaticMesh'/Engine/BasicShapes/Sphere.Sphere'"));
	static ConstructorHelpers::FObjectFinder<UMaterialInterface> MaterialAsset(TEXT("Material'/Engine/EditorMaterials/PersonaFloorMat.PersonaFloorMat'"));
	if (StaticMeshAsset.Succeeded() && MaterialAsset.Succeeded())//判断是否加载成功
	{
		//设置默认材质与材质球
		MyStaticMesh->SetStaticMesh(StaticMeshAsset.Object);
		MyStaticMesh->SetMaterial(0, MaterialAsset.Object);
		MyStaticMesh->SetWorldScale3D(FVector(0.5f));//设置默认缩放
	}

	MySpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("MySpringArm"));
	MySpringArm->SetupAttachment(GetStaticMeshComponent());
	MySpringArm->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f));//设置相对旋转
	MySpringArm->TargetArmLength = 400.0f;//无碰撞时弹簧臂的自然长度
	MySpringArm->bEnableCameraLag = true;//If true, camera lags behind target position to smooth its movement
	//如果bEnableCameraLag为真,则控制相机到达目标位置的速度。低值较慢(更多延迟),高值较快(更少延迟),而零是即时的(没有延迟)。
	MySpringArm->CameraLagSpeed = 3.0f; 

	MyCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("MyCamera"));
	//将摄像机附着到MySpringArm上
	MyCamera->SetupAttachment(GetSpringArmComponent());


	//决定哪个PlayerController(如果有的话)应该在关卡开始或生成小兵时自动拥有该小兵
	AutoPossessPlayer = EAutoReceiveInput::Player0;

	MaxSpeed = 100.0f;
	//等效于Velocity = FVector(0.0f,0.0f,0.0f);
	Velocity = FVector::ZeroVector;
}

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

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

	AddActorLocalOffset(Velocity * DeltaTime, true);
}

// Called to bind functionality to input
void AMyPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	//绑定移动函数
	PlayerInputComponent->BindAxis(TEXT("MoveForward"),this, &AMyPawn::MoveForward);
	PlayerInputComponent->BindAxis(TEXT("MoveRight"),this,&AMyPawn::MoveRight);

}

void AMyPawn::MoveForward(float Value)
{
	//FMath::Clamp(x,min,max)进行夹值
	Velocity.X = FMath::Clamp(Value, -1.0f, 1.0f) * MaxSpeed;
	
}

void AMyPawn::MoveRight(float Value)
{
	Velocity.Y = FMath::Clamp(Value, -1.0f, 1.0f) * MaxSpeed;
}
  • 运行结果
    在这里插入图片描述

设置静态网格为根组件

  • 因为Sweep扫描碰撞只对根组件有效,所以我们现在需要把根组件设置为静态网格体

  • 设置静态网格为根组件:直接将静态网格组件赋值为RootComponent即可

  • MyPawn.h

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

#pragma once

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

UCLASS()
class CPROJECT_API AMyPawn : public APawn
{
	GENERATED_BODY()

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

	//用class进行一下标明,遵循UE语法
	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class UStaticMeshComponent* MyStaticMesh;

	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class UCameraComponent* MyCamera;

	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class USpringArmComponent* MySpringArm;

	UPROPERTY(EditAnywhere, Category = "My Pawn Movement")
	float MaxSpeed;

	//接口
	FORCEINLINE UStaticMeshComponent* GetStaticMeshComponent() { return MyStaticMesh; }
	FORCEINLINE USpringArmComponent* GetSpringArmComponent() { return MySpringArm; }
	
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
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;


private:
	//创建两个移动函数,进行绑定
	void MoveForward(float Value);
	void MoveRight(float Value);
	FVector Velocity;
};
  • MyPawn.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyPawn.h"
#include "Camera/CameraComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "UObject/ConstructorHelpers.h"

// Sets default values
AMyPawn::AMyPawn()
{
 	// 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;
	
	MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));
	RootComponent = MyStaticMesh;//将StaticMesh设置为根组件
	MyStaticMesh->SetCollisionProfileName(TEXT("Pawn"));//设置静态网格默认碰撞为Pawn

	//添加默认材质与默认材质球
	static ConstructorHelpers::FObjectFinder<UStaticMesh> StaticMeshAsset(TEXT("StaticMesh'/Engine/BasicShapes/Sphere.Sphere'"));
	static ConstructorHelpers::FObjectFinder<UMaterialInterface> MaterialAsset(TEXT("Material'/Engine/EditorMaterials/PersonaFloorMat.PersonaFloorMat'"));
	if (StaticMeshAsset.Succeeded() && MaterialAsset.Succeeded())//判断是否加载成功
	{
		//设置默认材质与材质球
		MyStaticMesh->SetStaticMesh(StaticMeshAsset.Object);
		MyStaticMesh->SetMaterial(0, MaterialAsset.Object);
		MyStaticMesh->SetWorldScale3D(FVector(0.5f));//设置默认缩放
	}

	MySpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("MySpringArm"));
	MySpringArm->SetupAttachment(GetStaticMeshComponent());
	MySpringArm->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f));//设置相对旋转
	MySpringArm->TargetArmLength = 400.0f;//无碰撞时弹簧臂的自然长度
	MySpringArm->bEnableCameraLag = true;//If true, camera lags behind target position to smooth its movement
	//如果bEnableCameraLag为真,则控制相机到达目标位置的速度。低值较慢(更多延迟),高值较快(更少延迟),而零是即时的(没有延迟)。
	MySpringArm->CameraLagSpeed = 3.0f; 

	MyCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("MyCamera"));
	//将摄像机附着到MySpringArm上
	MyCamera->SetupAttachment(GetSpringArmComponent());


	//决定哪个PlayerController(如果有的话)应该在关卡开始或生成小兵时自动拥有该小兵
	AutoPossessPlayer = EAutoReceiveInput::Player0;

	MaxSpeed = 100.0f;
	//等效于Velocity = FVector(0.0f,0.0f,0.0f);
	Velocity = FVector::ZeroVector;
}

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

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

	AddActorLocalOffset(Velocity * DeltaTime, true);
}

// Called to bind functionality to input
void AMyPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	//绑定移动函数
	PlayerInputComponent->BindAxis(TEXT("MoveForward"),this, &AMyPawn::MoveForward);
	PlayerInputComponent->BindAxis(TEXT("MoveRight"),this,&AMyPawn::MoveRight);

}

void AMyPawn::MoveForward(float Value)
{
	//FMath::Clamp(x,min,max)进行夹值
	Velocity.X = FMath::Clamp(Value, -1.0f, 1.0f) * MaxSpeed;
	
}

void AMyPawn::MoveRight(float Value)
{
	Velocity.Y = FMath::Clamp(Value, -1.0f, 1.0f) * MaxSpeed;
}
  • 运行结果
    在这里插入图片描述
    在这里插入图片描述

控制视野上下旋转

  • 新增两个轴映射
    在这里插入图片描述

  • 在数学三维直角坐标系中里面XYZ也可以是,X:Roll,Y:Pitch,Z:Yaw,这是右手坐标系

  • 在UE中面XYZ也可以是,X:Pitch,Y:Yaw,Z:Roll,这是左手坐标系

  • 和移动Pawn差不多,新建两个接受映射函数,然后进行绑定,在到tick里面进行设置旋转

//新建两个接受映射函数
void LookUP(float Value);
void LookRight(float Value);
FVector2D MouseInput;
-----------------------------------------------------------------------------
//然后进行绑定
PlayerInputComponent->BindAxis(TEXT("LookUp"), this, &AMyPawn::LookUP);
PlayerInputComponent->BindAxis(TEXT("LookRight"), this, &AMyPawn::LookRight);
-----------------------------------------------------------------------------
//映射函数处理
void AMyPawn::LookUP(float Value)
{
	MouseInput.Y = FMath::Clamp(Value, -1.0f, 1.0f);
}

void AMyPawn::LookRight(float Value)
{
	MouseInput.X = FMath::Clamp(Value, -1.0f, 1.0f);
}
-----------------------------------------------------------------------------
//在到tick里面进行设置旋转
// Called every frame
void AMyPawn::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	AddActorLocalOffset(Velocity * DeltaTime, true);

	//在UE中面XYZ也可以是,X:Pitch,Y:Yaw,Z:Roll
	FRotator NewSpringArmRotation = MySpringArm->GetComponentRotation();//获取当前SpringArm旋转
	
	//设置抬头只能到80度,低头只能到0度
	NewSpringArmRotation.Pitch = FMath::Clamp(NewSpringArmRotation.Pitch += MouseInput.Y, -80.0f, 0.0f);
	
	//设置SpringArm旋转
	MySpringArm->SetWorldRotation(NewSpringArmRotation);
}
  • 运行结果就是可以鼠标移动上下视角

Controller控制视野左右旋转

  • 开启Controller继承,然后在Tick中添加鼠标传入的左右旋转值到Controller
    • bUseControllerRotationYaw= true;开启Controller Yaw方位继承
    • AddControllerYawInput(MouseInput.X); 添加鼠标传入的左右旋转值到Controller
  • MyPawn.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

UCLASS()
class CPROJECT_API AMyPawn : public APawn
{
	GENERATED_BODY()

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

	//用class进行一下标明,遵循UE语法
	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class UStaticMeshComponent* MyStaticMesh;

	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class UCameraComponent* MyCamera;

	UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")
	class USpringArmComponent* MySpringArm;

	UPROPERTY(EditAnywhere, Category = "My Pawn Movement")
	float MaxSpeed;

	//接口
	FORCEINLINE UStaticMeshComponent* GetStaticMeshComponent() { return MyStaticMesh; }
	FORCEINLINE USpringArmComponent* GetSpringArmComponent() { return MySpringArm; }
	
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
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;

private:
	//创建两个移动函数,进行绑定
	void MoveForward(float Value);
	void MoveRight(float Value);
	FVector Velocity;

	void LookUP(float Value);
	void LookRight(float Value);
	FVector2D MouseInput;
};
  • MyPawn.cpp
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyPawn.h"
#include "Camera/CameraComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "UObject/ConstructorHelpers.h"

// Sets default values
AMyPawn::AMyPawn()
{
 	// 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;
	
	MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));
	RootComponent = MyStaticMesh;//将StaticMesh设置为根组件
	MyStaticMesh->SetCollisionProfileName(TEXT("Pawn"));//设置静态网格默认碰撞为Pawn

	//添加默认材质与默认材质球
	static ConstructorHelpers::FObjectFinder<UStaticMesh> StaticMeshAsset(TEXT("StaticMesh'/Engine/BasicShapes/Sphere.Sphere'"));
	static ConstructorHelpers::FObjectFinder<UMaterialInterface> MaterialAsset(TEXT("Material'/Engine/EditorMaterials/PersonaFloorMat.PersonaFloorMat'"));
	if (StaticMeshAsset.Succeeded() && MaterialAsset.Succeeded())//判断是否加载成功
	{
		//设置默认材质与材质球
		MyStaticMesh->SetStaticMesh(StaticMeshAsset.Object);
		MyStaticMesh->SetMaterial(0, MaterialAsset.Object);
		MyStaticMesh->SetWorldScale3D(FVector(0.5f));//设置默认缩放
	}

	MySpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("MySpringArm"));
	MySpringArm->SetupAttachment(GetStaticMeshComponent());

	MySpringArm->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f));//设置相对旋转
	MySpringArm->TargetArmLength = 400.0f;//无碰撞时弹簧臂的自然长度
	MySpringArm->bEnableCameraLag = true;//If true, camera lags behind target position to smooth its movement
	//如果bEnableCameraLag为真,则控制相机到达目标位置的速度。低值较慢(更多延迟),高值较快(更少延迟),而零是即时的(没有延迟)。
	MySpringArm->CameraLagSpeed = 3.0f; 

	MyCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("MyCamera"));
	//将摄像机附着到MySpringArm上
	MyCamera->SetupAttachment(GetSpringArmComponent());

	//决定哪个PlayerController(如果有的话)应该在关卡开始或生成小兵时自动拥有该小兵
	AutoPossessPlayer = EAutoReceiveInput::Player0;

	//开启Controller继承
	bUseControllerRotationYaw = true;

	//移动速度
	MaxSpeed = 100.0f;
	//等效于Velocity = FVector(0.0f,0.0f,0.0f);
	Velocity = FVector::ZeroVector;
}

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

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

	AddActorLocalOffset(Velocity * DeltaTime, true);

	//添加鼠标传入的左右旋转值到Controller
	AddControllerYawInput(MouseInput.X);

	//在UE中里面也可以是X:Roll,Y:Pitch,Z:Yaw
	FRotator NewSpringArmRotation = MySpringArm->GetComponentRotation();//获取当前SpringArm旋转

	//设置抬头只能到80度,低头只能到0度
	NewSpringArmRotation.Pitch = FMath::Clamp(NewSpringArmRotation.Pitch += MouseInput.Y, -80.0f, 0.0f);

	//设置SpringArm旋转
	MySpringArm->SetWorldRotation(NewSpringArmRotation);
}

// Called to bind functionality to input
void AMyPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	//绑定移动函数
	PlayerInputComponent->BindAxis(TEXT("MoveForward"),this, &AMyPawn::MoveForward);
	PlayerInputComponent->BindAxis(TEXT("MoveRight"),this,&AMyPawn::MoveRight);
	PlayerInputComponent->BindAxis(TEXT("LookUp"), this, &AMyPawn::LookUP);
	PlayerInputComponent->BindAxis(TEXT("LookRight"), this, &AMyPawn::LookRight);

}

void AMyPawn::MoveForward(float Value)
{
	//FMath::Clamp(x,min,max)进行夹值
	Velocity.X = FMath::Clamp(Value, -1.0f, 1.0f) * MaxSpeed;
	
}

void AMyPawn::MoveRight(float Value)
{
	Velocity.Y = FMath::Clamp(Value, -1.0f, 1.0f) * MaxSpeed;
}

void AMyPawn::LookUP(float Value)
{
	MouseInput.Y = FMath::Clamp(Value, -1.0f, 1.0f);
}

void AMyPawn::LookRight(float Value)
{
	MouseInput.X = FMath::Clamp(Value, -1.0f, 1.0f);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值