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

  • 派生自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 propertiesAMyActor();protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual 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 propertiesAMyActor();//设置组件属性与种类UPROPERTY(VisibleAnyWhere, Category = "MyStatic")//定义一个静态组件UStaticMeshComponent* MyStatic;protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual 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 propertiesAMyActor();//设置组件属性与种类UPROPERTY(VisibleAnyWhere, Category = "MyStatic")//定义一个静态组件UStaticMeshComponent* MyStatic;UPROPERTY(EditInstanceOnly, Category = "MyActorProperties | Vector")//新建一个三维空间向量变量FVector InitLocation;protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual 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 propertiesAMyActor();//设置组件属性与种类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 spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual 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 propertiesAMyActor();//设置组件属性与种类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 spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual 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 propertiesAMyPawn();UPROPERTY(VisibleAnywhere, Category = "My Pawn Components")UStaticMeshComponent* MyStaticMesh;protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual 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 propertiesAMyPawn();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 spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual 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 propertiesAMyPawn();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 spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual 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 propertiesAMyPawn();//用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 spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual 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 propertiesAMyPawn();//用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 spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual 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 propertiesAMyPawn();//用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 spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual 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:YawFRotator 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 propertiesAMyPawn();//用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 spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual 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);//添加鼠标传入的左右旋转值到ControllerAddControllerYawInput(MouseInput.X);//在UE中里面也可以是X:Roll,Y:Pitch,Z:YawFRotator 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.rhkb.cn/news/175251.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

38基于matlab的期货预测,利用PSO优化SVM和未优化的SVM进行对比,得到实际输出和期望输出结果。

基于matlab的期货预测&#xff0c;利用PSO优化SVM和未优化的SVM进行对比&#xff0c;得到实际输出和期望输出结果。线性核函数、多项式、RBF核函数三种核函数任意可选&#xff0c;并给出均方根误差&#xff0c;相对误差等结果&#xff0c;程序已调通&#xff0c;可直接运行。 3…

谈API接入必须了解的各大API调用电商API应用场景

哪些业务场景可以使用API接口&#xff1f; &#xff08;1&#xff09;爬虫业务&#xff1a;在爬虫业务中&#xff0c;使用API接口可以帮助解决IP限制、反爬虫策略等问题&#xff0c;提高爬取数据的效率和稳定性。 &#xff08;2&#xff09;网络安全&#xff1a;在网络安全领…

虚拟化、容器与Docker基本介绍以及安装部署(Docker 基本管理)

虚拟化、容器与Docker基本介绍以及安装部署&#xff08;Docker 基本管理&#xff09; 1、Docker 概述1.1Docker与虚拟机的区别1.2容器在内核中支持2种重要技术&#xff1a;1.3Docker核心概念 2、安装docker服务docker安装步骤详解 3、 网络优化4、docker基本命令4.1查看镜像——…

代码随想录算法训练营第三十九天丨 动态规划part02

62.不同路径 思路 动态规划 机器人从(0 , 0) 位置出发&#xff0c;到(m - 1, n - 1)终点。 按照动规五部曲来分析&#xff1a; 确定dp数组&#xff08;dp table&#xff09;以及下标的含义 dp[i][j] &#xff1a;表示从&#xff08;0 &#xff0c;0&#xff09;出发&#…

荣电集团与钕希科技签署全面战略合作

10月26日&#xff0c;荣电集团&#xff08;以下简称荣电&#xff09;与钕希科技南京有限公司&#xff08;以下简称钕希科技&#xff09;今天在合肥市签署全面战略合作协议&#xff0c;联合进军混合现实&#xff08;Mixed Reality&#xff0c;以下简称MR&#xff09;空间计算高科…

leetcode-字符串

1.反转字符串LeetCode344. 20230911 难度为0&#xff0c;此处就不放代码了 注意reverse和swap等一系列字符串函数什么时候该用&#xff0c;记一记库函数 swap可以有两种实现&#xff0c;涨知识了&#xff0c;除了temp存值还可以通过位运算&#xff1a;s[i] ^ s[j]; s[j] ^ s[i…

【c++|opencv】二、灰度变换和空间滤波---1.灰度变换、对数变换、伽马变换

every blog every motto: You can do more than you think. https://blog.csdn.net/weixin_39190382?typeblog 0. 前言 灰度变换、对数变换、伽马变换 1. 灰度变换 #include <iostream> #include <opencv2/opencv.hpp>using namespace std; using namespace c…

03_Flutter自定义下拉菜单

03_Flutter自定义下拉菜单 在Flutter的内置api中&#xff0c;可以使用showMenu实现类似下拉菜单的效果&#xff0c;或者使用PopupMenuButton组件&#xff0c;PopupMenuButton内部也是使用了showMenu这个api&#xff0c;但是使用showMenu时&#xff0c;下拉面板的显示已经被约定…

Redis(10)| I/O多路复用(mutiplexing)

上文select/epoll 在上文《Redis&#xff08;09&#xff09;| Reactor模式》 思考问题可以使用I/O多路复用技术解决多多客户端TCP连接问题&#xff0c;同时也提到为了解决最早期的UNIX系统select调用存在的四个问题。 select(int nfds, fd_set *r, fd_set *w, fd_set *e, stru…

动手学深度学习——第七次学

LeNet&#xff08;LeNet-5&#xff09;由两个部分组成&#xff1a; 卷积编码器和全连接层密集块 卷积把高宽不断变小&#xff0c;把通道数逐渐增多&#xff0c;&#xff08;最后高宽会变成&#xff0c;通道会变得很大&#xff0c;然后做全连接进行输出&#xff09;通道信息可以…

7+共病思路。WGCNA+多机器学习+实验简单验证,易操作

今天给同学们分享一篇共病WGCNA多机器学习实验的生信文章“Shared diagnostic genes and potential mechanism between PCOS and recurrent implantation failure revealed by integrated transcriptomic analysis and machine learning”&#xff0c;这篇文章于2023年5月16日发…

人到中年应该怎么交朋友

听人劝、吃饱饭,奉劝各位小伙伴,不要订阅该文所属专栏。 作者:不渴望力量的哈士奇(哈哥),十余年工作经验, 跨域学习者,从事过全栈研发、产品经理等工作,现任研发部门 CTO 。荣誉:2022年度博客之星Top4、博客专家认证、全栈领域优质创作者、新星计划导师,“星荐官共赢计…

虚拟机克隆

linux系统的组成&#xff1b; 主根目录和根目录; 所有的根目录都包含在主根目录中&#xff1b; 根目录&#xff1a; /root /home/xxx,yyy,zzz;主根目录&#xff1b;/ 一个重要的子目录&#xff1a;etc passwd, 保存了所有的三类用户信息&#xff1b;bashrc, 可以设置别名 及…

HarmonyOS开发:基于http开源一个网络请求库

前言 网络封装的目的&#xff0c;在于简洁&#xff0c;使用起来更加的方便&#xff0c;也易于我们进行相关动作的设置&#xff0c;如果&#xff0c;我们不封装&#xff0c;那么每次请求&#xff0c;就会重复大量的代码逻辑&#xff0c;如下代码&#xff0c;是官方给出的案例&am…

阿里云推出通义千问App,提供全方位的协助

&#x1f989; AI新闻 &#x1f680; 阿里云推出通义千问App&#xff0c;提供全方位的协助 摘要&#xff1a;阿里云旗下大模型通义千问App登陆各大安卓应用市场&#xff0c;具有超大规模预训练模型&#xff0c;可在创意文案、办公助理、学习助手、趣味生活等方面协助用户。功…

Transformer.js简明教程【Web AI】

Transformers.js 可在你的 Web 浏览器中实现最先进的机器学习&#xff0c;无需服务器。 它提供预训练模型和熟悉的 API&#xff0c;支持自然语言处理、计算机视觉、音频和多模态领域的任务。 借助 Transformers.js&#xff0c;开发人员可以直接在浏览器中运行文本分类、图像分类…

RPC与HTTP的关系

首选理清楚关系 RPC与HTTP是两个不同维度的东西 HTTP 协议&#xff08;Hyper Text Transfer Protocol&#xff09;&#xff0c;又叫做超文本传输协议&#xff0c;是一种传输协议&#xff0c;平时通过浏览器浏览网页网页&#xff0c;用到的就是 HTTP 协议。 而 RPC&#xff0…

Flutter FittedBox

&#x1f525; 英文单词FittedBox &#x1f525; Fitted 通过有道翻译如下 &#xff1a; Box 通过有道翻译如下 &#xff1a; 对 FittedBox 的理解 我们可以将 FittedBox 理解为合适的盒子&#xff0c;将其它布局放到FittedBox这样一个盒子中&#xff0c;从而实现 盒子里面的…

ceph高可用

配置基础环境 # 关闭防火墙 systemctl stop firewalld systemctl disable firewalld# 关闭selinux setenforce 0 sed -i s/^SELINUX.*/SELINUXdisabled/ /etc/selinux/config 安装基础环境 然后安装ceph的密钥&#xff0c;centos7和8都要执行&#xff0c;下面不特别说明都是c…

一文详解汽车电子LIN总线

0.摘要 汽车电子LIN总线不同于CAN总线。 LIN总线基本上是CAN总线的廉价补充&#xff0c;相比于CAN总线&#xff0c;它提供较低的可靠性和性能。同时LIN总线也是一个应用非常广泛的网络协议&#xff0c;并且越来越受欢迎。 再一次&#xff0c;我们准备了一个关于LIN总线的简要…