在Unreal Engine中使用C++创建基础角色并添加移动功能

目录

引言

步骤一:创建C++类

步骤二:编写C++代码

步骤三:设置输入绑定

步骤四:在UE编辑器中测试

结论


引言

Unreal Engine(UE)以其强大的功能和灵活性在游戏开发界广受好评。本文将指导你如何在UE中通过C++创建一个基础的游戏角色,并为其添加基本的移动功能,如前进、后退、左转和右转。我们将从创建C++类开始,编写代码以实现这些功能,并在UE编辑器中测试它们。

步骤一:创建C++类
  1. 打开Unreal Engine Editor:启动UE4或UE5编辑器。

  2. 新建C++类:在UE编辑器中,选择“File” > “New C++ Class...”。

  3. 设置类属性

    • Parent Class:选择ACharacter作为父类,因为它已经包含了基础的移动组件和动画支持。
    • Class Name:为你的类命名,例如AMyCharacter
    • Class Folder:选择或创建一个文件夹来存放你的类文件。
    • 点击“Create Class”按钮。
步骤二:编写C++代码

在生成的AMyCharacter.hAMyCharacter.cpp文件中,我们将添加代码以实现基础移动功能。

AMyCharacter.h

// Fill out your copyright notice in the Description page of Project Settings.  
  
#pragma once  
  
#include "CoreMinimal.h"  
#include "GameFramework/Character.h"  
#include "MyCharacter.generated.h"  
  
UCLASS()  
class YOURPROJECTNAME_API AMyCharacter : public ACharacter  
{  
    GENERATED_BODY()  
  
public:      
    // Sets default values for this character's properties  
    AMyCharacter();  
  
protected:  
    // Called when the game starts or when spawned  
    virtual void BeginPlay() override;  
  
public:      
    // Called every frame  
    virtual void Tick(float DeltaTime) override;  
  
    // Called for forwards/backwards input  
    void MoveForward(float Value);  
  
    // Called for side to side input  
    void MoveRight(float Value);  
};

AMyCharacter.cpp

// Fill out your copyright notice in the Description page of Project Settings.  
  
#include "MyCharacter.h"  
  
AMyCharacter::AMyCharacter()  
{  
    // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.  
    PrimaryActorTick.bCanEverTick = true;  
  
    // Configure character movement  
    GetCharacterMovement()->bOrientRotationToMovement = true; // Rotate character to face movement direction  
    GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // Set the rotation rates for the character  
}  
  
void AMyCharacter::BeginPlay()  
{  
    Super::BeginPlay();  
    // Additional initialization can be done here  
}  
  
void AMyCharacter::Tick(float DeltaTime)  
{  
    Super::Tick(DeltaTime);  
  
    // This is just an example, actual input handling should be done in a PlayerController or InputComponent  
    // Assuming we have input values from somewhere (e.g., gamepad, keyboard)  
    // MoveForward(InputAxisValue);  
    // MoveRight(InputAxisValue);  
}  
  
void AMyCharacter::MoveForward(float Value)  
{  
    if ((Controller != nullptr) && (Value != 0.0f))  
    {  
        // Find out which way is forward  
        const FRotator Rotation = Controller->GetControlRotation();  
        const FVector Direction = FRotationMatrix(Rotation).GetUnitAxis(EAxis::X);  
  
        // Add movement in that direction  
        AddMovementInput(Direction, Value);  
    }  
}  
  
void AMyCharacter::MoveRight(float Value)  
{  
    if ((Controller != nullptr) && (Value != 0.0f))  
    {  
        // Find out which way is right  
        const FRotator Rotation = Controller->GetControlRotation();  
        const FVector Direction = FRotationMatrix(Rotation).GetUnitAxis(EAxis::Y);  
  
        // Add movement in that direction  
        AddMovementInput(Direction, Value);  
    }  
}

注意:上面的Tick函数中的MoveForwardMoveRight调用只是示例,实际上你通常会在SetupPlayerInputComponent函数中设置这些输入绑定,或者在你的PlayerController类中处理输入。

步骤三:设置输入绑定

AMyCharacter类中,我们需要重写SetupPlayerInputComponent函数来设置输入绑定。这个函数会在角色被创建时自动调用,以配置如何响应玩家的输入。

修改AMyCharacter.h

AMyCharacter类的声明中添加对SetupPlayerInputComponent函数的声明(如果尚未存在):

// ...  
protected:  
    // Function to bind player inputs  
    virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;  
// ...

修改AMyCharacter.cpp

实现SetupPlayerInputComponent函数:

void AMyCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)  
{  
    Super::SetupPlayerInputComponent(PlayerInputComponent);  
  
    // Bind axis movements to our custom functions  
    PlayerInputComponent->BindAxis("MoveForward", this, &AMyCharacter::MoveForward);  
    PlayerInputComponent->BindAxis("MoveRight", this, &AMyCharacter::MoveRight);  
  
    // Optionally, bind keys or buttons for specific actions  
    // PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &AMyCharacter::Jump);  
}

请注意,上面的"MoveForward""MoveRight"是输入轴(Axis)的名称,这些名称应该与你在UE编辑器中设置的输入轴名称相匹配,或者你可以在这里定义它们(尽管通常在项目的Project Settings -> Input中预先定义)。

步骤四:在UE编辑器中测试
  1. 编译你的项目:在UE编辑器中,点击“Compile”按钮来编译你的C++代码。

  2. 放置角色到场景中:在UE编辑器的内容浏览器中,找到你的AMyCharacter类,然后将其拖放到关卡编辑器中的场景中。

  3. 配置输入:如果你还没有在Project Settings -> Input中设置输入轴,现在需要设置。为"MoveForward""MoveRight"设置合适的输入设备(如键盘或游戏手柄)和按键/摇杆。

  4. 播放关卡:点击编辑器工具栏上的“Play”按钮来运行你的关卡,并测试你的角色是否按预期移动。

结论

通过上述步骤,你应该已经成功在Unreal Engine中使用C++创建了一个基础的游戏角色,并为其添加了基本的移动功能。这只是UE中C++编程的一个起点,你可以继续探索更复杂的角色行为、物理交互、AI控制等高级功能。

Unreal Engine 4 Scripting with C++ Cookbook 2016 | ISBN-10: 1785885545 | 431 pages | PDF | 7 MB Key Features A straightforward and easy-to-follow format A selection of the most important tasks and problems Carefully organized instructions to solve problems efficiently Clear explanations of what you did Solutions that can be applied to solve real-world problems Book Description Unreal Engine 4 (UE4) is a complete suite of game development tools made by game developers, for game developers. With more than 100 practical recipes, this book is a guide showcasing techniques to use the power of C++ scripting while developing games with UE4. It will start with adding and editing C++ classes from within the Unreal Editor. It will delve into one of Unreal's primary strengths, the ability for designers to customize programmer-developed actors and components. It will help you understand the benefits of when and how to use C++ as the scripting tool. With a blend of task-oriented recipes, this book will provide actionable information about scripting games with UE4, and manipulating the game and the development environment using C++. Towards the end of the book, you will be empowered to become a top-notch developer with Unreal Engine 4 using C++ as the scripting language. What you will learn Build function libraries (Blueprints) containing reusable code to reduce upkeep Move low-level functions from Blueprint into C++ to improve performance Abstract away complex implementation details to simplify designer workflows Incorporate existing libraries into your game to add extra functionality such as hardware integration Implement AI tasks and behaviors in Blueprints and C++ Generate data to control the appearance and content of UI elements
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值