Trang chủ » blog » Unreal Engine 4 C++ Tutorial

Unreal Engine 4 C++ Tutorial

In this Unreal Engine 4 tutorial, you will learn how to create C++ classes and expose variables and functions to the editor program. Blueprints is a very popular way to create gameplay in Unreal Engine 4. however, if you ’ re a long-time programmer and prefer sticking to code, C++ is for you ! Using C++, you can besides make changes to the engine and besides make your own plugins .
In this tutorial, you will learn how to :

  • Create C++ classes
  • Add components and make them visible to Blueprints
  • Create a Blueprint class based on a C++ class
  • Add variables and make them editable in Blueprints
  • Bind axis and action mappings to functions
  • Override C++ functions in Blueprints
  • Bind an overlap event to a function

Please bill that this is not a tutorial on learning C++. alternatively, this tutorial will focus on working with C++ in the context of Unreal Engine.

note : This tutorial assumes you already know the basics of using Unreal Engine. If you are raw to Unreal Engine, you should go through our 10-part Unreal Engine for Beginners tutorial serial first .

Getting Started

If you haven ’ metric ton already, you will need to install ocular Studio. Follow Epic ’ s official guide on setting up ocular Studio for Unreal Engine 4. ( Although you can use alternate IDEs, this tutorial will use ocular Studio as Unreal is already designed to work with it. )
Afterwards, download the starter stick out and unzip it. Navigate to the project booklet and clear CoinCollector.uproject. If it asks you to rebuild modules, chink Yes .
Unreal Engine 4 C++ Tutorial
once that is done, you will see the following view :
Unreal Engine 4 C++ Tutorial
In this tutorial, you will create a ball that the musician will control to collect coins. In former tutorials, you have been creating player-controlled characters using Blueprints. For this tutorial, you will create one using C++ .

Creating a C++ Class

To create a C++ course, go to the Content Browser and blue-ribbon Add New\New C++ Class .
Unreal Engine 4 C++ Tutorial
This will bring up the C++ Class Wizard. First, you need to select which class to inherit from. Since the class needs to be player-controlled, you will need a Pawn. Select Pawn and click Next .
Unreal Engine 4 C++ Tutorial
In the adjacent shield, you can specify the name and path for your .h and .cpp files. Change Name to BasePlayer and then click Create Class .
Unreal Engine 4 C++ Tutorial
This will create your files and then compile your plan. After compiling, Unreal will open Visual Studio. If BasePlayer.cpp and BasePlayer.h are not open, go to the Solution Explorer and open them. You can find them under Games\CoinCollector\Source\CoinCollector .
Unreal Engine 4 C++ Tutorial
Before we move on, you should know about Unreal ’ s reflection system. This system powers respective parts of the engine such as the Details dialog box and garbage solicitation. When you create a class using the C++ Class Wizard, Unreal will put three lines into your header :

  1. #include "TypeName.generated.h"
  2. UCLASS()

artificial requires these lines in ordain for a course to be visible to the contemplation system. If this sounds confusing, don ’ thymine worry. barely know that the reflection arrangement will allow you to do things such as disclose functions and variables to Blueprints and the editor .
You ’ ll besides notice that your class is named ABasePlayer alternatively of BasePlayer. When creating an actor-type class, Unreal will prefix the classify name with A ( for actor ). The reflection system requires classes to have the appropriate prefixes in order to work. You can read about the other prefixes in Epic ’ s Coding Standard .
note : Prefixes will not display within the editor program. For exercise, if you wanted to create a variable of type ABasePlayer, you would search for BasePlayer .
That ’ s all you need to know about the expression system for now. adjacent, you will add a musician model and camera. To do this, you need to use components .

Adding Components

For the player Pawn, you will add three components :

  1. Static Mesh: This will allow you to select a mesh to represent the player
  2. Spring Arm: This component operates like a camera boom. One end will be attached to the mesh and the camera will be attached to the other end.
  3. Camera: Whatever this camera sees is what Unreal will display to the player

first, you need to include headers for each type of part. open BasePlayer.h and then add the follow lines above #include "BasePlayer.generated.h" :

#include "Components/StaticMeshComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "Camera/CameraComponent.h"
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "Components/StaticMeshComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "Camera/CameraComponent.h"
#include "BasePlayer.generated.h"

note : It is crucial that the .generated.h file is the last include. In this casing, your includes should look like this : If it is not the last include, you will get an error when compose .
now you need to declare variables for each component. Add the stick to lines after SetupPlayerInputComponent() :

UStaticMeshComponent* Mesh;
USpringArmComponent* SpringArm;
UCameraComponent* Camera;

The name you use here will be the appoint of the component in the editor. In this encase, the components will display as Mesh, SpringArm and Camera .
adjacent, you need to make each variable visible to the reflection system. To do this, add UPROPERTY() above each variable. Your code should now look like this :

UStaticMeshComponent* Mesh;

USpringArmComponent* SpringArm;

UCameraComponent* Camera;

You can besides add specifiers to UPROPERTY(). These will control how the variable behaves with versatile aspects of the engine .
Add VisibleAnywhere and BlueprintReadOnly inside the brackets for each UPROPERTY(). Separate each specifier with a comma .

UPROPERTY(VisibleAnywhere, BlueprintReadOnly)

VisibleAnywhere will allow each component to be visible within the editor ( including Blueprints ) .
BlueprintReadOnly will allow you to get a reference to the component using Blueprint nodes. however, it will not allow you to set the component. It is important for components to be read-only because their variables are pointers. You do not want to allow users to set this differently they could point to a random localization in memory. eminence that BlueprintReadOnly will silent allow you to set variables inside of the part, which is the craved behavior .
note : For non-pointer variables ( int, float, boolean etc. ), use EditAnywhere and BlueprintReadWrite alternatively .
immediately that you have variables for each component, you need to initialize them. To do this, you must create them within the builder .

Initializing Components

To create components, you can use CreateDefaultSubobject("InternalName"). open BasePlayer.cpp and add the stick to lines inside ABasePlayer() :

Mesh = CreateDefaultSubobject("Mesh");
SpringArm = CreateDefaultSubobject("SpringArm");
Camera = CreateDefaultSubobject("Camera");

This will create a component of each type. It will then assign their memory address to the provided varying. The string controversy will be the part ’ s inner identify used by the engine ( not the display name although they are the lapp in this lawsuit ) .
Next you need to set up the hierarchy ( which component is the beginning and so on ). Add the keep up after the previous code :

RootComponent = Mesh;

The first line will make Mesh the ancestor component. The second line will attach SpringArm to Mesh. finally, the third line will attach Camera to SpringArm .
now that the part code is accomplished, you need to compile. Perform one of the come methods to compile :

  1. In Visual Studio, select Build\Build Solution
  2. In Unreal Engine, click Compile in the Toolbar

adjacent, you need to set which enmesh to use and the rotation of the form weapon. It is advisable to do this in Blueprints because you do not want to hard-code asset paths in C++. For model, in C++, you would need to do something like this to set a static engagement :

static ConstructorHelpers::FObjectFinder MeshToUse(TEXT("StaticMesh'/Game/MyMesh.MyMesh");

however, in Blueprints, you can barely select a mesh from a drop-down number .
Unreal Engine 4 C++ Tutorial
If you were to move the asset to another booklet, your Blueprints wouldn ’ thymine collapse. however, in C++, you would have to change every character to that asset .
To set the enmesh and give arm rotation within Blueprints, you will need to create a Blueprint based on BasePlayer .
note : It is common commit to create base classes in C++ and then create a Blueprint subclass. This makes it easier for roles such as artists and designers to edit classes .

Subclassing C++ Classes

In Unreal Engine, voyage to the Blueprints folder and create a Blueprint Class. Expand the All Classes section and search for BasePlayer. Select BasePlayer and then click Select .
Unreal Engine 4 C++ Tutorial
Rename it to BP_Player and then open it .
first, you will set the mesh topology. Select the Mesh part and set its Static Mesh to SM_Sphere .
Unreal Engine 4 C++ Tutorial
following, you need to set the spring branch ’ sulfur rotation and length. This will be a top-down game so the camera needs to be above the musician .
Select the SpringArm component and set Rotation to ( 0, -50, 0 ). This will rotate the spring arm so that the television camera points down towards the interlock .
Unreal Engine 4 C++ Tutorial
Since the spring weapon is a child of the mesh topology, it will start spinning when the ball starts spinning .
Unreal Engine 4 C++ Tutorial
To fix this, you need to set the rotation of the form arm to be absolute. Click the arrow next to Rotation and choose World .
Unreal Engine 4 C++ Tutorial
Afterwards, set Target Arm Length to 1000. This will place the television camera 1000 units away from the enmesh .
Unreal Engine 4 C++ Tutorial
next, you need to set the Default Pawn Class in order to use your Pawn. Click Compile and then go back to the editor program. Open the World Settings and set Default Pawn to BP_Player .
Unreal Engine 4 C++ Tutorial
Press Play to see your Pawn in the game .
Unreal Engine 4 C++ Tutorial
The future pace is to add functions so the actor can move approximately .

Implementing Movement

rather of adding an offset to move about, you will move around using physics ! First, you need a varying to indicate how much storm to apply to the ball .
Go back to Visual Studio and open BasePlayer.h. Add the following after the component variables :

UPROPERTY(EditAnywhere, BlueprintReadWrite)
float MovementForce;

EditAnywhere allows you to edit MovementForce in the Details control panel. BlueprintReadWrite will allow you to set and read MovementForce using Blueprint nodes .
future, you will create two functions. One for moving up and down and another for moving entrust and right .

Creating Movement Functions

Add the follow function declarations below MovementForce :

void MoveUp(float Value);
void MoveRight(float Value);

subsequently on, you will bind axis mapppings to these functions. By doing this, axis mappings will be able to pass in their scale ( which is why the functions need the float Value argument ) .
note : If you are not familiar with bloc mappings and scale, check out our Blueprints tutorial. nowadays, you need to create an execution for each function. open BasePlayer.cpp and add the following at the end of the file :

void ABasePlayer::MoveUp(float Value)
	FVector ForceToAdd = FVector(1, 0, 0) * MovementForce * Value;

void ABasePlayer::MoveRight(float Value)
	FVector ForceToAdd = FVector(0, 1, 0) * MovementForce * Value;

MoveUp() will add a physics force on the x-axis to Mesh. The lastingness of the effect is provided by MovementForce. By multiplying the consequence by Value ( the axis mapping scale ), the engage can move in either the positive or negative directions .
MoveRight() does the lapp as MoveUp() but on the Y-axis .
now that the motion functions are accomplished, you need to bind the axis mappings to them .

Binding Axis Mappings to Functions

For the sake of simplicity, I have already created the axis mappings for you. You can find them in the Project Settings under Input .
Unreal Engine 4 C++ Tutorial
note : Axis mappings do not need to have the lapp name as the function you are binding them to .
Add the watch inside SetupPlayerInputComponent() :

InputComponent->BindAxis("MoveUp", this, &ABasePlayer::MoveUp);
InputComponent->BindAxis("MoveRight", this, &ABasePlayer::MoveRight);

This will bind the MoveUp and MoveRight axis mappings to MoveUp() and MoveRight() .
That ’ s it for the movement functions. next, you need to enable physics on the Mesh component .

Enabling Physics

Add the surveil lines inside ABasePlayer() :

MovementForce = 100000;

The first line will allow physics forces to affect Mesh. The second gear line will set MovementForce to 100,000. This means 100,000 units of force will be added to the testis when moving. By nonpayment, physics objects weigh about 110 kilograms so you need a distribute of force to move them !
If you ’ ve created a subclass, some properties won ’ thymine change even if you ’ ve changed it within the base class. In this case, BP_Player won ’ t have Simulate Physics enabled. however, any subclasses you create now will have it enabled by default .
Compile and then go back to Unreal Engine. Open BP_Player and select the Mesh component. Afterwards, enable Simulate Physics .
Unreal Engine 4 C++ Tutorial
Click Compile and then press Play. Use W, A, S and D to move about .
Unreal Engine 4 C++ Tutorial
future, you will declare a C++ officiate that you can implement using Blueprints. This allows designers to create functionality without having to use C++. To learn this, you will create a leap serve .

Creating the Jump Function

first you need to bind the leap map to a affair. In this tutorial, jump is set to space prevention .
Unreal Engine 4 C++ Tutorial
Go back to Visual Studio and open BasePlayer.h. Add the following below MoveRight() :

UPROPERTY(EditAnywhere, BlueprintReadWrite)
float JumpImpulse;

void Jump();

First is a float variable called JumpImpulse. You will use this when implementing the jump. It uses EditAnywhere to make it editable within the editor. It besides uses BlueprintReadWrite so you can read and write it using Blueprint nodes .
adjacent is the leap function. UFUNCTION() will make Jump() visible to the reflection system. BlueprintImplementableEvent will allow Blueprints to implement Jump(). If there is no execution, any calls to Jump() will do nothing .
eminence : If you want to provide a default implementation in C++, use BlueprintNativeEvent alternatively. You ’ ll learn how to do this late on in the tutorial .
Since Jump is an action map, the method to bind it is slenderly different. Close BasePlayer.h and then open BasePlayer.cpp. Add the follow inside SetupPlayerInputComponent() :

InputComponent->BindAction("Jump", IE_Pressed, this, &ABasePlayer::Jump);

This will bind the Jump map to Jump(). It will only execute when you press the leap out key. If you want it to execute when the key is released, use IE_Released alternatively .
Up following is overriding Jump() in Blueprints .

Overriding Functions in Blueprints

Compile and then close BasePlayer.cpp. Afterwards, go back to Unreal Engine and overt BP_Player. Go to the My Blueprints panel and brood over Functions to display the Override drop-down. Click it and blue-ribbon Jump. This will create an event Jump .
Unreal Engine 4 C++ Tutorial
note : An override will be an event if there is no reappearance type. If there is a render type, it will be a function .
following, create the follow frame-up :
Unreal Engine 4 C++ Tutorial
This will add an momentum ( JumpImpulse ) on the Z-axis to Mesh. note that in this implementation, the musician can jump indefinitely .
future, you need to set the value of JumpImpulse. Click Class Defaults in the Toolbar and then go to the Details control panel. Set JumpImpulse to 100000 .
Unreal Engine 4 C++ Tutorial
Click Compile and then close BP_Player. Press Play and startle about using space bar .
Unreal Engine 4 C++ Tutorial
In the following section, you will make the coins disappear when the player touches them .

Collecting Coins

To handle overlaps, you need to bind a function to an overlap event. To do this, the function must meet two requirements. The first is that the officiate must have the UFUNCTION() macro. The second necessity is the function must have the compensate signature. In this tutorial, you will use the OnActorBeginOverlap event. This event requires a function to have the succeed signature :

FunctionName(AActor* OverlappedActor, AActor* OtherActor)

Go back to Visual Studio and open BaseCoin.h. Add the play along below PlayCustomDeath() :

void OnOverlap(AActor* OverlappedActor, AActor* OtherActor);

After binding, OnOverlap() will execute when the coin overlaps another actor. OverlappedActor will be the mint and OtherActor will be the other actor .
following, you need to implement OnOverlap() .

Implementing Overlaps

open BaseCoin.cpp and add the following at the end of the file :

void ABaseCoin::OnOverlap(AActor* OverlappedActor, AActor* OtherActor)

Since you only want to detect overlaps with the player, you need to cast OtherActor to ABasePlayer. Before you do the cast, you need to include the heading for ABasePlayer. Add the play along below #include "BaseCoin.h" :

#include "BasePlayer.h"

nowadays you need to perform the cast. In Unreal Engine, you can cast like this :


If the frame is successful, it will return a arrow to ObjectToCast. If abortive, it will return nullptr. By checking if the result is nullptr, you can determine if the object was of the right type .
Add the play along inside OnOverlap() :

if (Cast(OtherActor) != nullptr)

now, when OnOverlap() executes, it will check if OtherActor is of type ABasePlayer. If it is, destroy the mint .
adjacent, you need to bind OnOverlap() .

Binding the Overlap Function

To bind a routine to an overlap event, you need to use AddDynamic() on the event. Add the come inside ABaseCoin() :

OnActorBeginOverlap.AddDynamic(this, &ABaseCoin::OnOverlap);

This will bind OnOverlap() to the OnActorBeginOverlap event. This event occurs whenever this actor overlaps another actor .
Compile and then go back to Unreal Engine. Press Play and start collecting coins. When you overlap a mint, the mint will destroy itself, causing it to disappear .
Unreal Engine 4 C++ Tutorial
note : If the coins don ’ metric ton melt, try restarting the editor program to do a full recompile. Some code changes require a resume in orderliness to work .
In the following section, you will create another overridable C++ function. however, this time you will besides create a default execution. To demonstrate this, you will use OnOverlap() .

Creating a Function’s Default Implementation

To make a routine with a default option execution, you need to use the BlueprintNativeEvent specifier. Go back to Visual Studio and outdoors BaseCoin.h. Add BlueprintNativeEvent to the UFUNCTION() of OnOverlap() :

void OnOverlap(AActor* OverlappedActor, AActor* OtherActor);

To make a function the default implementation, you need to add the _Implementation suffix. open BaseCoin.cpp and change OnOverlap to OnOverlap_Implementation :

void ABaseCoin::OnOverlap_Implementation(AActor* OverlappedActor, AActor* OtherActor)

now, if a child Blueprint does not implement OnOverlap(), this implementation will be used alternatively .
The following step is to implement OnOverlap() in BP_Coin .

Creating the Blueprint Implementation

For the Blueprint implementation, you will call PlayCustomDeath(). This C++ function will increase the mint ’ s rotation pace. After 0.5 seconds, the coin will destroy itself .
To call a C++ function from Blueprints, you need to use the BlueprintCallable specifier. Close BaseCoin.cpp and then open BaseCoin.h. Add the follow above PlayCustomDeath() :


Compile and then near ocular Studio. Go back to Unreal Engine and open BP_Coin. Override On Overlap and then create the follow setup :
Unreal Engine 4 C++ Tutorial
now whenever a player overlaps a coin, Play Custom Death will execute .
Click Compile and then close BP_Coin. Press Play and collect some coins to test the modern execution .
unreal engine C++ tutorial

Where to Go From Here?

You can download the completed visualize hera .
As you can see, working with C++ in Unreal Engine is quite easy. Although you ’ ve accomplished a distribute so far with C++, there is still a lot to learn ! I ’ d commend checking out Epic ’ s tutorial serial on creating a top-down shot using C++ .
If you ’ re raw to Unreal Engine, check out our 10-part founder series. This serial will take you through diverse systems such as Blueprints, Materials and Particle Systems .
If there ’ s a topic you ’ d like me to cover, let me know in the comments below ! Weekly

The newsletter is the easiest direction to stay up-to-date on everything you need to know as a mobile developer .

Get a weekly digest of our tutorials and courses, and receive a free in-depth e-mail class as a bonus !

source :
Category : Economy

Post navigation

Leave a Comment

Trả lời

Email của bạn sẽ không được hiển thị công khai.