UE5 C++ 跑酷游戏练习 Part1

2024-06-19 00:20
文章标签 c++ 游戏 练习 跑酷 ue5 part1

本文主要是介绍UE5 C++ 跑酷游戏练习 Part1,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一.修改第三人称模板的 Charactor

1.随鼠标将四处看的功能的输入注释掉。

void ARunGANCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{// Set up action bindingsif (UEnhancedInputComponent* EnhancedInputComponent = CastChecked<UEnhancedInputComponent>(PlayerInputComponent)) {//JumpingEnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Triggered, this, &ACharacter::Jump);EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Completed, this, &ACharacter::StopJumping);//MovingEnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &ARunGANCharacter::Move);//Looking//EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &ARunGANCharacter::Look);}

2.在Tick里,注释掉计算左右方向的部分。只让它获得向前的方向。再加个每帧都朝,正前方输入的逻辑。

void ARunGANCharacter::Tick(float DeltaSeconds)
{Super::Tick(DeltaSeconds);GetController()->SetControlRotation(FMath::RInterpConstantTo(GetControlRotation(),DesireRotation,GetWorld()->GetRealTimeSeconds(),10.f));//const FRotator Rotation = Controller->GetControlRotation();const FRotator YawRotation(0, Rotation.Yaw, 0);// get forward vectorconst FVector ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);// get right vector //const FVector RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);//AddMovementInput(ForwardDirection, 1);
}

3.修改按下输入,调用的Move里的逻辑。让它如果转向,就按自己输入的X方向。旋转90度。

如果不转向,按照人物控制当前的朝向,计算左右的向量,并添加左右输入。

相当于一直向前跑,不转向可以左右调整。

if (bTurn)
{ //GEngine->AddOnScreenDebugMessage(-1,5.0f,FColor::Red,TEXT("Turn"));FRotator NewRotation = FRotator(0.f,90.f*(MovementVector.X), 0.f);FQuat QuatA = FQuat(DesireRotation);FQuat QuatB = FQuat(NewRotation);DesireRotation = FRotator(QuatA * QuatB);bTurn = false;
}
else
{// find out which way is forwardconst FRotator Rotation = Controller->GetControlRotation();const FRotator YawRotation(0, Rotation.Yaw, 0);// get forward vector//const FVector ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);// get right vector const FVector RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);//ForwardDirection = FVector(0,0,0);// add movement //AddMovementInput(ForwardDirection, 0);  //   AddMovementInput(RightDirection, MovementVector.X);/*	if (Controller->IsLocalPlayerController()){APlayerController* const PC = CastChecked<APlayerController>(Controller);}*///GetCharacterMovement()->bOrientRotationToMovement = false;//
}

4.这里转向的方向DesireRotation,会被一直赋值到控制器(Controller->GetControlRotation)。进而影响我们 向前方向。因为Tick里一直在修正。左右会在,Move回调函数里添加,也受控制器的影响。

void ARunGANCharacter::Tick(float DeltaSeconds)
{Super::Tick(DeltaSeconds);GetController()->SetControlRotation(FMath::RInterpConstantTo(GetControlRotation(),DesireRotation,GetWorld()->GetRealTimeSeconds(),10.f));//const FRotator Rotation = Controller->GetControlRotation();const FRotator YawRotation(0, Rotation.Yaw, 0);// get forward vectorconst FVector ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);// get right vector //const FVector RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);//AddMovementInput(ForwardDirection, 1);
}

人物逻辑就写好了,一直跑,Turn为True时转90.其余时间,相当于一直按W,你自己决定要不要A,D,斜向跑。

二.写碰撞,碰撞时,能实现转向。

创建TurnBox C++ Actor类。在里面,添加UBoxComponent组件,添加碰撞的回调函数。内容也很简单,如果是 角色碰撞,让它的装箱变量变为True。

#include "TurnBox.generated.h"class UBoxComponent;
UCLASS()
class RUNGAN_API ATurnBox : public AActor
{GENERATED_BODY()UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = Box,meta = (AllowPrivateAccess = "true"))UBoxComponent* Box;public:	// Sets default values for this actor's propertiesATurnBox();protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;UFUNCTION()void CharacterOverlapStart(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool  bFromSweep, const FHitResult& SweepResult);// UPrimitiveComponent, OnComponentBeginOverlap, UPrimitiveComponent*, OverlappedComponent, AActor*, OtherActor, UPrimitiveComponent*, OtherComp, int32, OtherBodyIndex, bool, bFromSweep, const FHitResult &, SweepResult);UFUNCTION()void CharacterOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);//UPrimitiveComponent*, OverlappedComponent, AActor*, OtherActor, UPrimitiveComponent*, OtherComp, int32, OtherBodyIndex);
};

这里实例化组件,就不写了。把角色的头文件,包含进去。绑定回调,回调里判断逻辑。

// Called when the game starts or when spawned
void ATurnBox::BeginPlay()
{Super::BeginPlay();	Box->OnComponentBeginOverlap.AddDynamic(this,&ATurnBox::CharacterOverlapStart);Box->OnComponentEndOverlap.AddDynamic(this, &ATurnBox::CharacterOverlapEnd);
}// Called every frame
void ATurnBox::Tick(float DeltaTime)
{Super::Tick(DeltaTime);}void ATurnBox::CharacterOverlapStart(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{if (ARunGANCharacter* InCharacter =  Cast<ARunGANCharacter>(OtherActor)){InCharacter->bTurn = true;}
}void ATurnBox::CharacterOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{if (ARunGANCharacter* InCharacter = Cast<ARunGANCharacter>(OtherActor)){InCharacter->bTurn = false;}
}

三.开始写路的逻辑,随机生成。

1.准备好道路资源

2.这里将道路,分为直道,转弯道,上下道。使用了UE创建枚举的方式。

#pragma once
#include"CoreMinimal.h"
#include "RunGANType.generated.h"
UENUM()
enum class FRoadType :uint8   //只需要一个字节,更高效 0-255
{StraitFloor,TurnFloor,UPAndDownFloor,MAX,
};

3.然后我们创建道路类,写上通用逻辑。在头文件,将道路类型加上,并前项声明 指针 指向的组件类。

#include "../../RunGANType.h"
#include "RunRoad.generated.h"
class UBoxComponent;
class USceneComponent;
class UStaticMeshComponent;
class UArrowComponent;UCLASS()
class RUNGAN_API ARunRoad : public AActor
{GENERATED_BODY()//场景组件UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "C_J", meta = (AllowPrivateAccess = "true"))USceneComponent* SceneComponent;//根组件UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "C_J", meta = (AllowPrivateAccess = "true"))USceneComponent* RunRoadRootComponent;//碰撞UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "C_J",meta = (AllowPrivateAccess = "true"))UBoxComponent* BoxComponent;//模型UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "C_J",meta = (AllowPrivateAccess = "true"))UStaticMeshComponent* RoadMesh;//方向UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "C_J",meta = (AllowPrivateAccess = "true"))UArrowComponent* SpawnPointMiddle;UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "C_J",meta = (AllowPrivateAccess = "true"))UArrowComponent* SpawnPointRight;UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "C_J",meta = (AllowPrivateAccess = "true"))UArrowComponent* SpawnPointLeft;//地板类型UPROPERTY(EditDefaultsOnly,Category = "TowerType")  //EditDefaultsOnly:蓝图可以编译,但是在主编译器不显示所以不可以编译FRoadType RoadType;public:	// Sets default values for this actor's propertiesARunRoad();FTransform GetAttackToTransform(const FVector& MyLocation);
protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;UFUNCTION()void CharacterOverlapStart(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool  bFromSweep, const FHitResult& SweepResult);// UPrimitiveComponent, OnComponentBeginOverlap, UPrimitiveComponent*, OverlappedComponent, AActor*, OtherActor, UPrimitiveComponent*, OtherComp, int32, OtherBodyIndex, bool, bFromSweep, const FHitResult &, SweepResult);UFUNCTION()void CharacterOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);

4.实现逻辑

#include"Components/BoxComponent.h"
#include"Components/SceneComponent.h"
#include"Components/StaticMeshComponent.h"
#include"Components/ArrowComponent.h"

CreateDefaultSubobject<T>实例化组件,SetupAttachment添加组件,Root根组件,Father在根组件下,其余在Father组件下。

ARunRoad::ARunRoad()
{// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = false;//generateBox = CreateDefaultSubobject<UBoxComponent>(TEXT("GenerateBox"));//实例化SceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Father"));RunRoadRootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));RootComponent = RunRoadRootComponent;RoadMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("RoadMesh"));BoxComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("Box"));SpawnPointMiddle = CreateDefaultSubobject<UArrowComponent>(TEXT("SpawnPointMiddle"));SpawnPointRight = CreateDefaultSubobject<UArrowComponent>(TEXT("SpawnPointRight"));SpawnPointLeft = CreateDefaultSubobject<UArrowComponent>(TEXT("SpawnPointLeft"));//附加顺序SceneComponent->SetupAttachment(RootComponent);RoadMesh->SetupAttachment(SceneComponent);BoxComponent->SetupAttachment(SceneComponent);SpawnPointMiddle->SetupAttachment(SceneComponent);SpawnPointRight->SetupAttachment(SceneComponent);SpawnPointLeft->SetupAttachment(SceneComponent);
}

这样初步就将路结构搭建好了。后续开始写GameMode生成每一个路面。

这篇关于UE5 C++ 跑酷游戏练习 Part1的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1073482

相关文章

C++ 中的 if-constexpr语法和作用

《C++中的if-constexpr语法和作用》if-constexpr语法是C++17引入的新语法特性,也被称为常量if表达式或静态if(staticif),:本文主要介绍C++中的if-c... 目录1 if-constexpr 语法1.1 基本语法1.2 扩展说明1.2.1 条件表达式1.2.2 fa

C++中::SHCreateDirectoryEx函数使用方法

《C++中::SHCreateDirectoryEx函数使用方法》::SHCreateDirectoryEx用于创建多级目录,类似于mkdir-p命令,本文主要介绍了C++中::SHCreateDir... 目录1. 函数原型与依赖项2. 基本使用示例示例 1:创建单层目录示例 2:创建多级目录3. 关键注

C++从序列容器中删除元素的四种方法

《C++从序列容器中删除元素的四种方法》删除元素的方法在序列容器和关联容器之间是非常不同的,在序列容器中,vector和string是最常用的,但这里也会介绍deque和list以供全面了解,尽管在一... 目录一、简介二、移除给定位置的元素三、移除与某个值相等的元素3.1、序列容器vector、deque

C++常见容器获取头元素的方法大全

《C++常见容器获取头元素的方法大全》在C++编程中,容器是存储和管理数据集合的重要工具,不同的容器提供了不同的接口来访问和操作其中的元素,获取容器的头元素(即第一个元素)是常见的操作之一,本文将详细... 目录一、std::vector二、std::list三、std::deque四、std::forwa

C++字符串提取和分割的多种方法

《C++字符串提取和分割的多种方法》在C++编程中,字符串处理是一个常见的任务,尤其是在需要从字符串中提取特定数据时,本文将详细探讨如何使用C++标准库中的工具来提取和分割字符串,并分析不同方法的适用... 目录1. 字符串提取的基本方法1.1 使用 std::istringstream 和 >> 操作符示

C++原地删除有序数组重复项的N种方法

《C++原地删除有序数组重复项的N种方法》给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度,不要使用额外的数组空间,你必须在原地修改输入数组并在使用O(... 目录一、问题二、问题分析三、算法实现四、问题变体:最多保留两次五、分析和代码实现5.1、问题分析5.

C++ 各种map特点对比分析

《C++各种map特点对比分析》文章比较了C++中不同类型的map(如std::map,std::unordered_map,std::multimap,std::unordered_multima... 目录特点比较C++ 示例代码 ​​​​​​代码解释特点比较1. std::map底层实现:基于红黑

C++中函数模板与类模板的简单使用及区别介绍

《C++中函数模板与类模板的简单使用及区别介绍》这篇文章介绍了C++中的模板机制,包括函数模板和类模板的概念、语法和实际应用,函数模板通过类型参数实现泛型操作,而类模板允许创建可处理多种数据类型的类,... 目录一、函数模板定义语法真实示例二、类模板三、关键区别四、注意事项 ‌在C++中,模板是实现泛型编程

利用Python和C++解析gltf文件的示例详解

《利用Python和C++解析gltf文件的示例详解》gltf,全称是GLTransmissionFormat,是一种开放的3D文件格式,Python和C++是两个非常强大的工具,下面我们就来看看如何... 目录什么是gltf文件选择语言的原因安装必要的库解析gltf文件的步骤1. 读取gltf文件2. 提

C++快速排序超详细讲解

《C++快速排序超详细讲解》快速排序是一种高效的排序算法,通过分治法将数组划分为两部分,递归排序,直到整个数组有序,通过代码解析和示例,详细解释了快速排序的工作原理和实现过程,需要的朋友可以参考下... 目录一、快速排序原理二、快速排序标准代码三、代码解析四、使用while循环的快速排序1.代码代码1.由快