虚幻C++基础 day1

news2024/11/19 2:30:47

虚幻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子类

  • 派生自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(VisbleInstanceOnly,Category = “MyActorProperties | Vector”)
    • VisbleInstanceOnly:只运行在示例上进行显示
    • 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;
}
  • 运行结果
    在这里插入图片描述
    在这里插入图片描述

控制视野上下旋转

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

  • 在UE中里面XYZ也可以是,X:Roll,Y:Pitch,Z:Yaw

  • 和移动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中里面也可以是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);
}
  • 运行结果就是可以鼠标移动上下视角

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);
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1150172.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

编译环境里存在yaml-cpp的多个版本时可能引起的问题

有时要编译的程序自带了特定版本的yaml-cpp&#xff0c;同时系统目录下也安装了更高版本的yaml-cpp&#xff0c;这时可能引起编译错误&#xff0c;就是某些yaml-cpp的API不认识&#xff0c;例如&#xff1a; 出现这种问题倒好办&#xff0c;正常情况下不可能&#xff0c;肯定能…

目标检测算法发展史

前言 比起图像识别&#xff0c;现在图片生成技术要更加具有吸引力&#xff0c;但是要步入AIGC技术领域&#xff0c;首先不推荐一上来就接触那些已经成熟闭源的包装好了再提供给你的接口网站&#xff0c;会使用别人的模型生成一些图片就能叫自己会AIGC了吗&#xff1f;那样真正…

电脑突然提示找不到msvcp140.dll怎么办,解决msvcp140.dll丢失的办法

当我们在电脑上运行某些软件或游戏时&#xff0c;可能会遇到一个常见的错误消息&#xff1a;“找不到msvcp140.dll”。出现这样的情况通常意味着系统缺少一个重要的动态链接库文件&#xff0c;而这可能会导致程序无法正常启动。如果你现在遇到了这个问题&#xff0c;哪有可以用…

人大与加拿大女王大学金融管理硕士项目:开启国际视野,成就金融领袖

生活中&#xff0c;我们总会遇到各种各样的困难和挑战。有时候&#xff0c;我们会感到沮丧、迷茫甚至绝望。但是&#xff0c;正是这些困难和挑战&#xff0c;让我们变得更加坚强、勇敢和成熟。在这个职场竞争愈发激烈的时代&#xff0c;不断地充实自己是非常重要的。如果你从事…

Echats-页面切换时echats图表刷新

在src文件夹下的composables创建echats.ts echats.ts的内容为&#xff1a; import { nextTick, effectScope, onScopeDispose, ref, watch } from vue; import type { ComputedRef, Ref } from vue; import * as echarts from echarts/core; import { BarChart, GaugeChart, L…

Golang | Zinx学习笔记(一)

参考 http://zinx.me/ https://www.kancloud.cn/aceld/zinx/1960213 https://www.yuque.com/aceld/tsgooa/gx01meg5ow4pftac 说明 zinx是一个基于Golang的轻量级并发服务器框架。 目前zinx已经在很多企业进行开发使用&#xff0c;具体使用领域包括:后端模块的消息中转、长链…

Mybatis-Plus通用枚举功能 [MyBatis-Plus系列] - 第493篇

历史文章&#xff08;文章累计490&#xff09; 《国内最全的Spring Boot系列之一》 《国内最全的Spring Boot系列之二》 《国内最全的Spring Boot系列之三》 《国内最全的Spring Boot系列之四》 《国内最全的Spring Boot系列之五》 《国内最全的Spring Boot系列之六》 S…

win 下安装 nvm 的使用与配置

nvm 全名 node.js version management&#xff0c;是一个 nodejs 的版本管理工具。通过它可以安装和切换不同版本的 nodejs。 注&#xff1a;如果已经安装了 nodejs 需先卸载后再安装 nvm 为了确保 nodejs 已彻底删除&#xff0c;可以看看安装目录中是否有 node 文件夹&#x…

Linux|安装Nomachine

参考&#xff1a;2022 Nomachine 最简安装与使用指南&#xff08;https://blog.csdn.net/qq_51116518/article/details/127450253&#xff09; 解压 先将目录调整到压缩包所在目录&#xff0c;输入sudo tar zxvf nomachine_7.6.2_3_aarch64.tar.gz 添加权限 sudo chmod -R…

基于Cmake+QT+VS的C++项目构建开发编译简明教程

目前项目是尽量利用开源项目为基础&#xff0c;考虑到跨平台&#xff0c;以及后期便于开发的协同和延续&#xff0c;开发语言基于C/C、UI基于QT&#xff08;5.7.1&#xff09;&#xff0c;集成开发环境&#xff08;IDE&#xff09;使用Visual Studio&#xff08;2015&#xff0…

开心要笑,不开心就待会儿再笑,生活亦如此

90白鸭绒填充&#xff0c;给宝贝满满的安全感 厚实细腻上身真的很舒适&#xff0c;而且不会显得臃肿哦 杜邦三防面料的优点 防水防油防污&#xff0c;耐脏又实穿&#xff01;&#xff01;

Spring Cloud之API网关(Zuul)

目录 Zuul 简介 功能 工作流程 搭建 1.引入依赖 2.添加注解 3.路由转发 4.测试 实现原理 EnableZuulProxy注解 ZuulServlet FilterProcessor Zuul内置过滤器 常用配置 Zuul 简介 zuul是SpringCloud子项目的核心组件之一&#xff0c;可以作为微服务架构中的API网…

MappingMongoConverter原生mongo 枚举类ENUM映射使用的是name

j.l.IllegalArgumentException: No enum constant com.xxx.valobj.TypeEnum.stringat java.lang.Enum.valueOf

dracut添加指定固件

文章目录 linux-firmware1、固件介绍2、Microcode updates for CPUs3、如何添加固件 linux-firmware 1、固件介绍 存放在 /lib/firmware&#xff0c;固件来自kernel 仓库更多的固件可以参考git仓库&#xff0c;https://git.kernel.org/pub/scm/linux/kernel/git/firmware/lin…

day16_IO

今日内容 1.复习 2.IO 3.Hutool 4.Idea会导jar包 一、File[熟悉] 1.1 介绍 文件和目录(文件夹) 路径名的抽象表示形式。 即使用路径来表示一个文件或者一个文件夹对象 路径: 相对路径,相对于当前项目的项目名下绝对路径,按照磁盘来确定 1.2 构造方法 File(String pathname) 通…

从 Hash索引、二叉树、B-Tree 与 B+Tree 对比看索引结构选择

从 Hash索引、二叉树、B-Tree 与 BTree 对比看索引结构选择 1、Hash 结构1.1、关于 Hash 数据结构1.2、InnoDB索引为啥不选 Hash 结构1.3、关于InnoDB 提供自适应 Hash 索引 &#xff08;Adaptive Hash Index&#xff09; 2、二叉搜索树3、平衡二叉树&#xff08;AVL树 &#x…

EMQX内置Web管理控制台-Dashboard

一、Dashboard概述 EMQX Dashboard官网文档&#xff1a;https://docs.emqx.com/zh/enterprise/v5.1/dashboard/introduction.html 1、简介 EMQX 为用户提供了一个功能强大的内置管理控制台&#xff0c;即 EMQX Dashboard。通过这个控制台的 Web 界面&#xff0c;用户可以轻松监…

基于STM32闭环步进电机控制系统设计

**单片机设计介绍&#xff0c;1654基于STM32闭环步进电机控制系统设计&#xff08;仿真&#xff0c;程序&#xff0c;说明&#xff09; 文章目录 一 概要二、功能设计设计思路 三、 软件设计原理图 五、 程序文档 六、 文章目录 一 概要 基于STM32的闭环步进电机控制系统设计是…

劳动安全无小事,劳保安全鞋为您的足部安全保驾护航

安全生产责任重于泰山。日常说到劳动防护&#xff0c;人们往往先想到的是安全帽、工作服、安全带等身体与头部的防护&#xff0c;从而足部的伤害是较容易被人们所忽视的。其实脚部的防护至关重要&#xff0c;我们在日常工作中常见的足部伤害有&#xff1a;冲击、撞击伤害&#…