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++ 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提供个模板形参的名

6.1.数据结构-c/c++堆详解下篇(堆排序,TopK问题)

上篇:6.1.数据结构-c/c++模拟实现堆上篇(向下,上调整算法,建堆,增删数据)-CSDN博客 本章重点 1.使用堆来完成堆排序 2.使用堆解决TopK问题 目录 一.堆排序 1.1 思路 1.2 代码 1.3 简单测试 二.TopK问题 2.1 思路(求最小): 2.2 C语言代码(手写堆) 2.3 C++代码(使用优先级队列 priority_queue)

【C++高阶】C++类型转换全攻略:深入理解并高效应用

📝个人主页🌹:Eternity._ ⏩收录专栏⏪:C++ “ 登神长阶 ” 🤡往期回顾🤡:C++ 智能指针 🌹🌹期待您的关注 🌹🌹 ❀C++的类型转换 📒1. C语言中的类型转换📚2. C++强制类型转换⛰️static_cast🌞reinterpret_cast⭐const_cast🍁dynamic_cast 📜3. C++强制类型转换的原因📝

基于UE5和ROS2的激光雷达+深度RGBD相机小车的仿真指南(五):Blender锥桶建模

前言 本系列教程旨在使用UE5配置一个具备激光雷达+深度摄像机的仿真小车,并使用通过跨平台的方式进行ROS2和UE5仿真的通讯,达到小车自主导航的目的。本教程默认有ROS2导航及其gazebo仿真相关方面基础,Nav2相关的学习教程可以参考本人的其他博客Nav2代价地图实现和原理–Nav2源码解读之CostMap2D(上)-CSDN博客往期教程: 第一期:基于UE5和ROS2的激光雷达+深度RG

C++——stack、queue的实现及deque的介绍

目录 1.stack与queue的实现 1.1stack的实现  1.2 queue的实现 2.重温vector、list、stack、queue的介绍 2.1 STL标准库中stack和queue的底层结构  3.deque的简单介绍 3.1为什么选择deque作为stack和queue的底层默认容器  3.2 STL中对stack与queue的模拟实现 ①stack模拟实现

国产游戏崛起:技术革新与文化自信的双重推动

近年来,国产游戏行业发展迅猛,技术水平和作品质量均得到了显著提升。特别是以《黑神话:悟空》为代表的一系列优秀作品,成功打破了过去中国游戏市场以手游和网游为主的局限,向全球玩家展示了中国在单机游戏领域的实力与潜力。随着中国开发者在画面渲染、物理引擎、AI 技术和服务器架构等方面取得了显著进展,国产游戏正逐步赢得国际市场的认可。然而,面对全球游戏行业的激烈竞争,国产游戏技术依然面临诸多挑战,未来的