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++中实现调试日志输出

《C++中实现调试日志输出》在C++编程中,调试日志对于定位问题和优化代码至关重要,本文将介绍几种常用的调试日志输出方法,并教你如何在日志中添加时间戳,希望对大家有所帮助... 目录1. 使用 #ifdef _DEBUG 宏2. 加入时间戳:精确到毫秒3.Windows 和 MFC 中的调试日志方法MFC

深入理解C++ 空类大小

《深入理解C++空类大小》本文主要介绍了C++空类大小,规定空类大小为1字节,主要是为了保证对象的唯一性和可区分性,满足数组元素地址连续的要求,下面就来了解一下... 目录1. 保证对象的唯一性和可区分性2. 满足数组元素地址连续的要求3. 与C++的对象模型和内存管理机制相适配查看类对象内存在C++中,规

在 VSCode 中配置 C++ 开发环境的详细教程

《在VSCode中配置C++开发环境的详细教程》本文详细介绍了如何在VisualStudioCode(VSCode)中配置C++开发环境,包括安装必要的工具、配置编译器、设置调试环境等步骤,通... 目录如何在 VSCode 中配置 C++ 开发环境:详细教程1. 什么是 VSCode?2. 安装 VSCo

C++11的函数包装器std::function使用示例

《C++11的函数包装器std::function使用示例》C++11引入的std::function是最常用的函数包装器,它可以存储任何可调用对象并提供统一的调用接口,以下是关于函数包装器的详细讲解... 目录一、std::function 的基本用法1. 基本语法二、如何使用 std::function

Python开发围棋游戏的实例代码(实现全部功能)

《Python开发围棋游戏的实例代码(实现全部功能)》围棋是一种古老而复杂的策略棋类游戏,起源于中国,已有超过2500年的历史,本文介绍了如何用Python开发一个简单的围棋游戏,实例代码涵盖了游戏的... 目录1. 围棋游戏概述1.1 游戏规则1.2 游戏设计思路2. 环境准备3. 创建棋盘3.1 棋盘类

【C++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名