Getting Started with Game Development using Unreal Engine 4

In my humble opinion, Unreal Engine 4 is one of the most powerful game engines that exist right now, and the Epic Games team has released a license for all user, for just 19 USD a month.

This first tutorial gives an introduction to UE4. We will create the basis for our game by having a character walk through a level. We will use a fixed camera and basic game controls. This simple start will allow us to:

– Learn how to import 3D models to the project.
– Create the necessary classes to control the character.
– Understand the philosophy followed by Unreal’s framework in its classes model.
– Give an introduction to programming in Unreal Engine using C++ language.
– Understand the communication between the C++ classes and the Unreal Editor.
– Know the animation mechanism of the character.
– Introduce Visual Scripting using the Blueprint Editor.

Getting Unreal Engine 4

Getting the game engine is simple. First, you need to register at https://www.unrealengine.com/register and pay the 19 USD. Trust me, it will probably be the best 19 USD you ever spend. After you’ve paid and registered, you’ll have access to the same tools that the Epic Games team work with.

The next step is to actually get the engine. There are two ways to do this. The first way is launching the Launcher application. This application will allow us to download the latest version of the engine. The other way is to build the engine from the source code. That’s right, we have access to all the source code of the engine.

The official website gives a good explanation on the steps needed to download and build the source code from https://github.com/EpicGames/UnrealEngine/releases We’ll leave this topic here. If you have any problems with this process, please leave me a comment.

Model and Animations of the Main 3D Character

First thing we need to start our game is the main 3D character’s model and its animations. All of the 3D models that are used in a game, including the characters, objects, environments and animations, are created by the designers and animators of our team. We use modeling and animation 3D tools like 3DsMax or Blender. When the modeling and animation processes are over, the resulting model is exported with its skeleton and animations in the FBX format.

The 3D modeling and animation isn’t my strongest suit☺. Let’s start with the FBX resources from one of the sample projects released with UE4. This is exactly what our designer’s team will give us. You can download the resource from: https://d26ilriwvtzlb.cloudfront.net/a/a7/ThirdPerson_FBX.zip

Extract the contents of the .zip file. For now we will only work with the HeroTPP.FBX, Walk.FBX and Idle.FBX files. If you have any 3D modeling software, such as Maya 3D, you can import these files into the software, interact with them and examine them.

HeroTPP.FBX file loaded in Maya 2015. Skeleton view.

HeroTPP.FBX file loaded in Maya 2015. Skeleton view.

HeroTPP.FBX file loaded in Maya 2015. Model view.

HeroTPP.FBX file loaded in Maya 2015. Model view.

 

Hero.FBX is the 3D model of our main character along with its skeleton that will allow us to animate the model. Idle.FBX and Walk.FBX are, as the name suggests, the idle and walk animations. These last two files don’t contain any model because a model isn’t necessary in animation files. Animation files only hold information about the skeleton’s movement. That’s why there’s no need to export the 3D model when we export the animations.

Creating a New Project in Unreal Engine 4

Now that we are ready to begin, let’s start by creating the project. This is a very simple task in UE. We need to open the editor. The editor will show a window with two tabs: the Project tab, that contains all the previously created projects, and the New Project tab, that as its name suggests, allow us to create a new project.

A cool feature when creating a new project is a project group called Templates that we can use as base for our game. Using this, we can select the type of game that we want to develop. The available options are: 3rd Person, 1st Person, Top-Down or Side-Scroller.

Our goal in this first tutorial is only to offer an introduction to UE4. We aren’t going to use any of these relatively advanced templates. Instead, we’re going to create our project practically from scratch. We will select the Basic Template option. Select New Project/Basic Code. In the text field below type in the name of your project. In my case, I will use UE4Demo. Finally, we click the Create Project button.

Window to create and open a Project in Unreal Engine 4.

Window to create and open a Project in Unreal Engine 4.

This will create the project and will automatically open the IDE according to the operating system we’re using, Visual Studio 2013 in Windows case and XCode 5.1 in MAC OS. This tutorial is being developed in MAC OS so I’m using XCode as my IDE. Once the IDE has opened the project, we have to compile the project so we can open the Editor. Click in the upper-left corner to select “Scheme UE4DemoEditor-Mac” and then the “Product/Build For/Running” menu option.

The building process might take a while. Once it’s over we can select the “Product/Run” XCode menu option. This will prompt the Editor with our project opened.

Unreal Engine 4 Editor with our new Project just opened.

Unreal Engine 4 Editor with our new Project just opened.

UE4 provides us a scene with some objects added to it. For now, let’s leave the scene this way. You can select the Play button from toolbar to see all of the objects that compose our current scene. By default, we the control the camera with the mouse and keyboard. We could move through the whole scene, but this isn’t our goal. We will like to add our character to this world :)

Importing our character 3D model.

We already have our 3D models exported as FBX files with its skeleton and its two basic animations☺. Now let’s import them into our Project. In the left-bottom corner panel of the Editor we have the Content Browser. This panel is where we will have all of our game resources. Select the New Folder option and give it a name to the folder. For instance, “Character”. After this operation we have a new folder in the content browser. Go into this folder, select “Import” and search the FBX file of the character: HeroTPP.FBX (we will be importing the FBX files of the animation later on). Remember that this FBX file contains the 3D model and its skeleton. Select “OK” and the FBX “Import” window will appear. The Skeletal Mesh associated with the file will automatically be selected.

FBX Import window of Unreal Engine 4

FBX Import Window of Unreal Engine 4

Let’s take a break and theorize a little. As you can see in this import window, there are three types of resources that could be imported from a FBX file: a Static Mesh, a Skeletal Mesh and an Animation.

Static Mesh: A static object of our game. For instance, a chair, a building, the environment are static meshes. In other words, a Static Mesh is a 3D model without an animations or a skeleton.

Skeletal Mesh: Exactly the opposite of a Static Mesh and also the type of model that we’re importing. A Skeleton Mesh is a 3D model with an associated skeleton that can be animated. So to be clear, all the characters of our game will have a Skeletal Mesh.

Animation: Animations contain the transformation information of each of the bones of a skeleton to bring it to life when performing actions such as walking, jumping, etc. Examples of this are the Idle.FBX and Walk.FBX that we will soon import.

UE4 automatically detects that we’re importing a Skeletal Mesh so isn’t necessary to change anything. The default parameters are suitable to our purpose. The only thing left to do is to click the Import button. Ignore any warnings received during the import process. In the following tutorials, we’ll see the whole Export/Import process and the Animation Rigging Toolset provided to us by Epic Games to prepare the animations and models.

Once the model is imported in the Content Browser, we’ll have three new elements: Hero (SkeletalMesh), Hero_PhysicsAsset (PhysicsAsset) and Hero_Skeleton (Skeleton).

If you double click in the SkeletalMesh, you can open the imported model in the Persona Editor of UE4. Persona is the Skeleton, Skeletal Meshes, Animations Blueprints and other animations elements Editor in UE4.

The Skeletal Mesh of our character in the Persona Editor

The Skeletal Mesh of our character in the Persona Editor

When opening the Skeletal Mesh in the Persona Editor, we have on the left side the Skeleton Tree. This skeleton tree is composed of all of the bones that make up the skeleton’s model. At the bottom, we have the Mesh Details Panel. This is composed of several sections that describe the materials applied to the selected model. At the moment, we don’t have any material. Or rather, we only have the default material that gives an opaque view to our character.

The Hero_PhysicsAsset is the PhysicsAsset generated automatically during the process of importing the Skeletal Mesh. For now, we won’t use this asset. In future tutorials, we will see what it is used for, but if you’re a curious person double click on it, it will open the UE4 specific editor for this kind of assets. In the left-upper corner, there is a Simulate button. Click on the button and see what happens. This will give you an idea of the goal of this resource, generated automatically when importing the Skeletal Mesh.

Finally, the Hero_Skeleton is the model’s skeleton that we’ve just imported. A brilliant feature of UE4 is that we’re able to share the same skeleton between different 3D models that look relatively similar. So instead of importing the 3D model and its skeleton for each of these similar looking models, we will import the skeleton only once and then we will associate the skeleton with the different models.

So now that we’ve all the resources associated with the main character in our project, we’re able to start the main part — the coding :).

Introduction to Programming in Unreal Engine 4

A project in UE4 is basically composed of two big pieces that work together. The levels, which are developed on the Editor, and the programming project that is developed in our programming IDE. We already saw how when we created a project in UE4, the engine creates both of these pieces. We will now focus on the second part, the code.

The programming language used in UE4 is C++. When creating a new UE4 project, a C++ is automatically generated. This C++ project can be edited in XCode if you use MAC OS or Visual Studio if you use Windows. This project already contains the basic classes of our game. Open your IDE and select the project just created. The source code for our game, UE4Demo, is contained in the Source files. All of the UE4 framework source code is contained in the Engine files. The possibility of having access to this framework code is amazing because we are able to inspect the implementation of the framework classes or what is used for a certain property. This code is commented by Epic Games Team. Before we create our first class, we will quickly discuss some comments about the philosophy followed by UE4 in its framework.

In UE4, all the elements that appear in our game are Actors (in other words they inherit of the AActor class). For example, a chair, table, enemy or even the main character are all actors. The game elements that are controlled, non-static, and have a behavior are known as Pawns. There is a special kind of Pawn called Character. This is the Pawn that represents the main character and contains the particular implementations designed only for the model controlled by the gamer. For instance, if in our game we have a main character and an enemy, the first one will be a character and the second one will be a Pawn. All Pawns are controlled by a class called Controller. The Character is controlled by the PlayerController class. The PlayerController class receives input from the game and uses data to control the character in the game. Basically, the PlayerController object represents the human actions in the game. All non-player characters pawns are controlled by the AIController class.

It’s a little bit tricky at first, but bit by bit you will become familiarized with UE4 and come to understand its philosophy, class hierarchy, and their relations.

In the source code for our game, we have a file with the same name as our project. In my case, this file is called UE4Demo. Inside this file are a few classes that we can start working with.

The first class we are going to review is UE4DemoGameMode. This class defines our game’s Game Mode. The Game Mode describes the game’s rules, such as the win and lose conditions. The Game Mode also has the responsibility of defining the PlayerController and the default Pawn, among other things. UE4DemoGameMode is the core of the game. If we open the .h file, we will notice that this class inherits from AGameMode and for now doesn’t contain anything else.

//AUE4DemoGameMode.h
#pragma once

#include "GameFramework/GameMode.h"
#include "UE4DemoGameMode.generated.h"

UCLASS()
class AUE4DemoGameMode : public AGameMode
{
    GENERATED_UCLASS_BODY()
};

The class declaration contains two macros that should have caught your attention: UCLASS() and GENERATED_UCLASS_BODY.

UE4 has a strong system for the object handling. The base class for the objects in Unreal is UObject and the UCLASS macro should be used in classes that inherit from UObject. This informs the UObjects system handler of the existence of the new class.

When including these macros in our classes, we ensure that they have access to some of Unreal’s low level mechanisms, such as garbage collection, serialization, automatic initialization of properties, automatic editor integration, and more.

Now let’s see our GameMode implementation. As you can see, in UE4DemoGameMode.cpp, only the constructor is implemented.


//AUE4DemoGameMode.cpp
#include "UE4Demo.h"
#include "UE4DemoGameMode.h"
#include "UE4DemoPlayerController.h"

AUE4DemoGameMode::AUE4DemoGameMode(const class FPostConstructInitializeProperties& PCIP)
    : Super(PCIP)
{
    PlayerControllerClass = AUE4DemoPlayerController::StaticClass();
}

For now, the constructor only contains the initialization of the PlayerControllerClass attribute. This PlayerController for our game will act as an interface between the user and the character. In here, we initialize the PlayerControllerClass with a static instance of our own UE4DemoPlayerController. That’s why we can move like a ghost through the whole level when we run the project.

We already have a PlayerController but so far we don’t have a Character that represents the physical body of the character. The UE4DemoPlayerController class previously created is the PlayerController implementation for our game. This is empty at the moment. For now, we don’t need to personalize it. All that we need to control our character is already in the APlayerController class. We’re going to leave this class for now but can come back later when we need to add some custom behavior.

That’s enough theory for now. Let’s code!

We’ve already imported all the resources for our character in the Editor, so now let’s bring it to the scene :)

Creating our First Class in UE4

The first thing we’re going to do is to give life to our character, so we will create our character class. As I said earlier, the class in charge of controlling the character is the Pawn class. This is a special kind of Pawn, a Character, that’s why our class has to inherit from it.

The easiest way to add a new class to the project is through the Editor. Go back to the Editor. In the main menu, select “File/Add Code to Project”. Now a window will prompt to select the base class. As we already said we will use Character as our base class. In this window, you can inspect the most common UE4 classes and read a brief description on each of them. So select “Character” and hit the next button. Type in the name of your class. I will use HeroCharacter. Finally, end the class creation process. When the process completed, you will be asked if you want to open the IDE. Select OK and when the IDE opens, our newly created class will be there. The class structure was already described earlier. A class that inherits from ACharacter includes the UCLASS and GENERATED_UCLASS_BODY() macros that import the low level mechanisms (garbage collection etc.) from UE4.

Configuring the Character from the Blueprint Editor

We’ve configure our main character so this is a good time to make a personal comment about one of the mechanisms of UE4 that was very difficult for me to get used to because I came from a background of 2D game development. In game engines like Cocos2d, the majority of game logic and building is done using code. In UE4, the work philosophy is very different. Here we have two options for making our game. The first option is to do things by hand coding. This can cause us to have a slower rhythm in the production of code and is susceptible to bugs. The second option is by using the Editor. The downside of this option is that this new method of programming for can difficult for us programmers to adjust to. In this tutorial, we will work in the Editor or by code in the IDE. We leave the decision to you to choose which method to use to perform different tasks.

To demonstrate the UE4 integration between the code and the Editor, we will configure our character in both ways. This will let us show how amazing the communication between the C++ code and the editor is.

Now that we have our own class to represent the Character, let’s configure its components from the Editor. The first step is to open the Editor. In the Toolbar, we have the Blueprints button. Go ahead and select Blueprints/New Class Blueprint. In the bottom of the prompted window is a section named Custom classes. In that section, search and select the class we’ve just created for our Character, HeroCharacter. Name it, for instance as HeroCharacterBlueprint, and select the folder Game/Character to store the file. Once the process has finished, the Blueprint Editor will open up in the Components mode where we will configure our Character.

imagen_06

In the left side of the editor, we have the Components panel. As its name suggests, this panel contains all the components that compose the Character. The bottom panel shows the properties of the selected component. The CharacterMovements is the component that handles the movement of the Character. For example, here we hold the Max Walk Speed that is the top speed with which our character will be able to move. There are many more properties, and I recommend you to take a quick look over some of these properties to have an overview of all all the things that are configurable regarding movement.

The other component that the Character has is the CapsuleComponent. The CapsuleComponent is in charge of the collision detection. In the Viewport of the Editor, you can see it graphically as a transparent capsule, which represents the collision zone of the character.

At last, inside the CapsuleComponent we have a Mesh and I’m sure you already figured it out that is the Mesh that represents our character. There is also an ArrowComponent which informs us of the direction of the Character.

The only thing left is to finish the configuration of the Mesh. We must select the mesh component in the Component panel and the skeletal mesh property in the Details panel in the Mesh section. Select the dropdown and select the Skeletal Mesh of our character, the one we created when our hero FBX file was imported. We will see our hero model in the viewport. Use the translation and rotation tools to place the Mesh inside the CapsuleComponent and match the direction to the ArrowComponent. Finally, click the Save button in the upper-right corner of the Editor, and now we’ve given a body to our character. Let’s try it out. Close the Editor and run the game to see what we’ve so far.

Character’s Mesh in the right position in the HeroCharacterBlueprint

Character’s Mesh in the right position in the HeroCharacterBlueprint

:( As you noticed there are no changes. We still have game controls thanks to the default PlayerController, but we don’t have yet our character. The problem is that there are some things that we still have to setup.

First, make sure you have properly configured the GameMode. Click in the World Settings button of the Toolbar and make sure that you selected our UE4DemoGameMode class in the GameMode section. Under GameMode are all the elements configured for our game mode. For instance, in the PlayerControllerClass section, we have our PlayerController (UE4DemoPlayerController). Due to that in the UE4DemoGameMode constructor we initialize this property, but Pawn Class has the Default Pawn value, so we’re not over yet. The problem is that we created our character and gave it a body but we haven’t defined in the GameMode/Pawn Class that our HeroCharacter class is our character. Let’s do this by code, once again to demonstrate the amazing communication between the Editor and the code. So next we’re going to close the Editor and open the C++ project, search the UE4DemoGameMode class and modify the constructor implementation to match the below code:

AUE4DemoGameMode::AUE4DemoGameMode(const class FPostConstructInitializeProperties& PCIP)
    : Super(PCIP)
{
    PlayerControllerClass = AUE4DemoPlayerController::StaticClass();
    
    //Gets in PlayerPawnBPClass.Object the HeroCharacterBlueprint class created and configure from the Editor
    static ConstructorHelpers::FObjectFinder<UClass> PlayerPawnBPClass(TEXT("Class'/Game/Character/HeroCharacterBlueprint.HeroCharacterBlueprint_C'"));
    
    if (PlayerPawnBPClass.Object != NULL)
    {
        DefaultPawnClass = PlayerPawnBPClass.Object;
    }
}

Let’s take a minute to explain step by step what we just did cause even if you are an experienced C++ developer the previous syntax could be tricky. In the first line, we search and get the instance of HeroCharacter created in the Editor through the Blueprint Editor. Next we create a variable of FObjectFinder type, this is a public parameterized structure that holds inside another structure this one named ConstructerHelpers. FObjectFinder receives in its constructor the address of the object that we will instantiate, if the object is found successfully its instance it’s stored in the Object property.

It might be useful to seize the opportunity to review the framework source code. You can see the implementation of all structures, such as ConstructorHelpers, FObjectFinder, etc. In XCode, all you need to do is click the name while pressing the cmd key and you’ll be taken to the structure declaration. So take a minute to familiarize with these new structures in order to understand how they work. Also, you must note that to define the route to FObjectFinder we use the TEXT macro. This macro is used for all strings in the engine in order for the compiler to convert the string to the right data type, which in this case is a TCHAR*.

So now we have in PlayerPawnBPClass.Object the instance of our Character (PlayerPawnBPClass is the name that we gave to the variable that we created of FObjectFinder type). The only thing left is to initialize the DefaultPawnClass with this object. The GameMode class has the DefaultPawnClass attribute. This represents the Pawn that our character will use and we only have to set our class.

Now we are ready to play. Compile and execute the game. When the game starts our character is automatically added to the level. This is the level created by default for the selected template in the project creation. The level has an Actor of type Player Start. When the game starts, it searches for an instance of Player Start and adds our character at this position. The bad news is that now we lose the game controls so we are unable to move through the scene and the camera point of view is now the character’s eyes :( Temporarily, we solve this by setting a static camera in our game.

Setting a static camera by code.

Right click inside the viewport in the editor and select the folding menu Place Actor/Camera. Use the translation tools and transformations to aim the camera in the Play Start direction so we will be able to see the character. This is how I did it:

imagen_08

Now let’s inform Unreal that the game view will be taken from this camera. For this we have to come back once again to the theory.

We already discussed how according to Unreal philosophy, PlayerController is the interface between the main character of the game and the human being. So it’s completely natural that the logic regarding the game view will be implemented in this class. PlayerController has the SetViewTargetWithBlend method. This method allows us to control the camera point of view. We will call this method to set the camera we created as the game’s camera. We can change the camera’s point of view any time we want to. In this case, we will configure it to the direction of the camera that we created. In order to do that I will introduce you to one of the most used events in Unreal, the BeginPlay event. All classes that inherit from AActor have this method which is called, as its name suggests, when the game is about to start. Let’s add this method to our PlayerController class (that inherits from AActor) and change the game camera.

Open UE4DemoPlayerController.h file and add the next line: virtual void BeginPlay() override; below the GENERATED_UCLASS_BODY() macro, with this declaration we’re able to override the base class method and define our customized behavior. Go on to the .cpp file to define the method. Add the below code under the class constructor. I recommend you thoroughly review the comments so you can understand what we are doing in each step.

/** Inherit method of the AActor class it’s called automatically by the engine when the game starts. */
void AUE4DemoPlayerController::BeginPlay()
{
    //Call to the Begin Play method in the base class.
    Super::BeginPlay();
    
    //We iterate among all the actors in the level through the TActorIterator
    //TActorIterator is a parametrized iterator that allow us to iterate among all actors in the level.
    for (TActorIterator<ACameraActor> It(GetWorld()); It; ++It)
    {
        //We get the current actor in the loop. As we only have an ACameraActor in the level, the iterator will iterate only once.
        ACameraActor* _mainCamera = *It;
        
        //We configure the new point of view of the camera as our game view.
        //SetViewTargetWithBlend can receive more parameters, but the method has default values and in this case we won’t need more specialization so we’ll leave like this.
        this->SetViewTargetWithBlend(_mainCamera);
    }
}

We’re ready. Compile and run the game. Now you can see the level and our character viewed from the camera that we created.

Setting up a static camera through the Blueprint Editor.

I’ll take a break to talk about the Blueprint Editor. I’m sure that when you start in UE4 you asked yourself the same question that I did when I started – how do I do this? Through the Blueprint Editor or coding it in C++? The answer is a question of taste. As you advance in UE4 you will know which one is the best option for each task.

In order to compare both methods the next thing we will do is to setup the camera like we just did by code using the Blueprint Editor without typing a single line of code. Keep in mind that not all tasks are the same, so maybe the one that you find simplest now won’t be the best option in another case. In the Editor’s toolbar, click the Blueprint button and select the Open Level Blueprint option. This will open a blueprint file that concerns all of the logic for the whole level.

Following the logic that we use in C++, the first thing to do is to implement the BeginPlay event. The Blueprint Editor is a visual scripting editor, so basically we’re still programming but graphically (yes I know this sounds a little crazy at first☺). In here, we can add new variables, system events, specific functions classes, etc., Basically, you can do nearly everything that you can do in C++.

To add the BeginPlay event, right click in the center of the screen and uncheck the Context Sensitive option and search the Begin Play event. We’ve added a node that represents the event to our visual script. Next we will get the reference to the level’s camera and call the SetViewTargetWithBlend method in the PlayerController class passing the camera as parameter. To get a reference to the PlayerController, remember this is a “global” script in the “Level” level and the C++ implementation was made inside the PlayerController. Add a new node of the Get Player Controller type. This node returns the reference to the PlayerController of the game. Now we need to call the SetViewTargetWithBlend. Again we add a new node with the method’s name and now we have all the elements that we need to complete our visual algorithm. There is only one thing left, connect all the nodes.

Our first node (BeginPlay) has a port that represents the output, in other words, the execution of the call to this method. The SetViewTargetWithBlend node has both an input and an output ports. Click the first node port and drag the arrow to the input port of the method node. Release it when a green mark appears. Now when the game starts, the BeginPlay event will be executed and this will call the SetViewTargetWithBlend method. This method belongs to the PlayerController class so we need to define which is its PlayerController. The Get PlayerController node has an output port titled Return value we will connect this port with the SetViewTargetWithBlend port named Target. In doing that, we are defining the reference to the method. Remember that we also have to pass another parameter, the Actor, which we will use to configure the camera point of view. Finally, we need to add the camera node. Save these changes. Close the editor and select in the level the camera was previously added. Now open the editor once again, right click and you will notice that you have a shortcut to add a Camera Actor node. Once added, connect the output port of the camera actor to the New View Target port of the SetViewTargetWithBlend. Now we are done, our visual script is complete. Click the upper-left corner button Compile.

Before we play the game, let’s delete the override declaration and definition of the Begin Play event in the C++ code. You can comment it out if you want to so you don’t lose the code. Close the editor and comment out the UE4DemoPlayerController.h class in the code. Do the same in the .cpp file.

Compile and run the game. As you’ll notice, we’ve achieved the same result☺. So I repeat once again it’s your call either to choose the Editor or the code. You will have to wait to gain your own experiences and find out about the pros and cons of each method.

I recommend you take a break here because we’ve reached the middle of the tutorial and there are many more things to come :)

Setting the character’s animations

So far we only have our static character viewed from a fixed camera, which isn’t very functional, so let’s give it more life.

Remember that our design team :) also gave us the character’s skeleton and the walk and idle animations ready to be imported. Open the Editor and create a new folder in the Content Browser. I named the folder Animations. Open the folder and import the two FBX files: Walk.FBX and Idle.FBX. There is an option that allows us to select the skeleton associated with the animation being imported in the importation process. Select the Hero_Skeleton and click the Import button to finish the process.

Now you can inspect both files. Double click on one of them in the Content Browser and the Persona Editor will open showing a preview of the animations. From this Editor you can see all the animations details, play it and so much more that well have to cover that in future tutorials. The only thing left is to associate the animations with the character.

Creating the state machine and updating the character with the idle and walk animations using the Animation Blueprints

The Animation Blueprint is the tool that UE4 provide us to implement all the animation logic in a really simple way, using the state machines and visual scripting.

So let’s create the Animation Blueprint for our character. In the Content Browser, go to the Animations folder, right click in an empty space and select Animation/Animation Blueprint. This will open the Animation Blueprint window. In the Parent Class section, select AnimInstance and below Target Skeleton section write the name of the skeleton that uses our hero, Hero_Skeleton, and finish the process by clicking on the OK button.

The engine will automatically add an AnimBlueprint to the Content Browser with its name selected in case that you want to change it. Name it whatever you like. I will name it HeroAnimBlueprint. Before we do anything in the blueprint, let’s define that our character will use this blueprint to control its animation. To do this, search in the Content Browser where your character’s blueprint is, in my case is in: Game/Character/HeroCharacterBlueprint, and double click it. In the upper-right corner select the Defaults mode and you will see a section named Animation. In the Animation Mode property, select Use Animation Blueprint and in the Anim Blueprint Generated Class, select the class that we create HeroAnimBlueprint_C. Now we are ready. Save and close the Editor.

imagen_09

Now that everything is well configured, let’s open the HeroAnimBlueprint. This will open the Persona Editor. Right from the start we’ve a node Final Animation Pose. We will connect this node to the output of the node that we’re about to create, but first, as usual, a little bit of theory.

In UE4, we have an amazing and intuitive mechanism to define which animations to play for characters based on the state of the character. For example, if the character is resting, the idle animation will be played but if the character is walking, the walk animation will be the one played. You can do blending between the animations in order to ease the changes between them. In this case, we need define if the character is in the idle state or the walking state. We’ll do this by adding a “velocity” attribute, and say that if this variable value is 0 then the character is idle so the idle animation must be played, but if the velocity value is anything other than 0, the walk animation should be played. We can do all of this through a state machine and visual scripting in the Animation Blueprint.

Next we create the state machine. Inside the AnimBlueprint Editor, right click and select StateMachine/Add State Machine. This will add a state machine node type to the scene. Change its name to something more descriptive, such as HeroStateMachine, or something else you prefer. Now, inside the state machine we define states that our character will have. Double click on the state machine node to edit it. Inside you will find a node named Entry. Right click, select Add State, and name the created node Idle. Now connect, as we did in the level blueprint, the output port of the Entry node to the input port of the Idle node just created.

Now that all is clear, let’s define the Idle state logic. Double click on the node to edit it, then right click and select Animation/Play Idle. This adds the node that represents the Idle animation that we previously imported into the Editor. Finally, connect this node to the Final Animation Pose node.

Let’s check how all the connections are set in each and every one of the levels. From inside to outside, we have the Play Idle node connected to the Final Pose Animation node. In the upper level (HeroStateMachine), we have the Entry node connected to the idle node. Lastly, in the most upper level (AnimGraph), the HeroStateMachine node connected to the Final Animation Pose. Click the compile button in the upper-right corner of the editor. Notice that in the left panel that you can see a preview of the character with the idle animation.

imagen_10.1

imagen_10.2

imagen_10.3

Run the game. Here is our character in its rest state and with the idle animation.

Main character in the game in rest playing the idle animation.

Main character in the game in rest playing the idle animation.

Setting the game controls

So far, we’ve created and set our character, a temporary fixed camera, and the character’s first animation. The next step, as I’m sure you’ve already guessed, will be to make our character walk :)

First of all, we need to define the game controls. In order to do this, go to UE Editor’s menu Edit/Project Settings, Engine/Input section, Bindings block, click the + button in Axis Mapping and unfold the arrow, in the writing field type MoveForward. Click the arrow aside the EditText and unfold the field and select the W key and set a 1.0 value in the scale. Click again in the + aside the MoveForward’s EditText and select in the new combobox the S key and set -1.0 in the scale.

Now click in the + sign of Axis Mappings to create another section at the same level of MoveForward. In the new EditText, write MoveRight and add two children: A with Scale of -1 and D with 1.

imagen_12

We just defined our game controls. We need to give these game controls names to be able to call this entry from code and the value selected in the combobox is the control that will call this action. The scale value is a numeric value that can be retrieved in the code as a parameter. Generally, this value will be either -1 and 1. Another thing to notice is that the scale value allows us to define actions under the same identifier (MoveForward) and define both directions, given it a positive value of 1 and a negative of -1.

Now let’s code our character logic to move through the scene with this controls. This is fairly simple but enough to understand how it all works out. Basically we will need two things: Override the virtual void SetupPlayerInputComponent(class UInputComponent* InputComponent) method of APawn class to register the callbacks that will be called when the entries just created (MoveForward and MoveRight) are pressed. Also, we need to implement the character movement according to the entry pressed.

Open the HeroCharacter.h class and modify it to match the code below:

UCLASS()
class AHeroCharacter : public ACharacter
{
    GENERATED_UCLASS_BODY()
    
protected:
    
    /**
     * Is called when the engine detects the configured entry to 'MoveForward'.
     * In this case when the user press the W or S keys
     */
    void MoveForward(float Value);
    
    /**
     * Is called when the engine detects the configured entry to 'MoveRight'.
     * In this case when the user press the A or D keys
     */
    void MoveRight(float Value);
    
    /**
     * APawn class method that allows to configure the controls binding
     * Is called automatically by the Engine
     */
    virtual void SetupPlayerInputComponent(class UInputComponent* InputComponent) OVERRIDE;
    
};

So far, we simply defined two methods where we will implement the logic when one of the keys that we defined is pressed and we also added the SetupPlayerInputComponent method statement to our class in order to override it.

Next, go to the corresponding .cpp file and modify it like this:

#include "UE4Demo.h"
#include "HeroCharacter.h"


AHeroCharacter::AHeroCharacter(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{

}

void AHeroCharacter::SetupPlayerInputComponent(class UInputComponent* InputComponent)
{
    //Informs the engine that when the MoveForward entry is detected call AHeroCharacter::MoveForward method
    InputComponent->BindAxis("MoveForward", this, &AHeroCharacter::MoveForward);
    
    // Informs the engine that when the MoveRight entry is detected call AHeroCharacter:: MoveRight method
    InputComponent->BindAxis("MoveRight", this, &AHeroCharacter::MoveRight);
}


/**
*   It gets called when the MoveForward entry is detected (When the keys W or S are pressed)
*  Calculates the direction of the character and applies it a movement (positive or negative) in that direction.
*
*  @param Value is equal to 1 when W is pressed and -1 when S is.
*/
void AHeroCharacter::MoveForward(float Value)
{
    if ((Controller != NULL) && (Value != 0.0f))
    {
         //Gets the current rotation
        const FRotator Rotation = Controller->GetControlRotation();
        
         // Creates the direction vector and applies the movement
        const FVector Direction = FRotationMatrix(Rotation).GetUnitAxis(EAxis::X);
        AddMovementInput(Direction, Value);
    }
}

/**
*   It gets called when the MoveForward entry is detected (When the keys W or S are pressed)
*  @param Value is equal to 1 when D is detected and to -1 when A is detected.
*/
void AHeroCharacter::MoveRight(float Value)
{
    if ( (Controller != NULL) && (Value != 0.0f) )
    {
        //Determines the direction of the side movements. Notice that we only have interest in the rotation in the Y axis.
        const FRotator Rotation = Controller->GetControlRotation();
        const FRotator YawRotation(0, Rotation.Yaw, 0);
        
         // Creates the direction vector and applies the movement
        const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
        AddMovementInput(Direction, Value);
    }
}

In here, we’ve a couple of things to comment, but I’m sure by now you already have some thoughts about it. In SetupPlayerInputComponent, we use the method’s parameter to set the callbacks that will be called when an entry is detected. In other words, with InputComponent->BindAxis(“MoveForward”, this, &AHeroCharacter::MoveForward); we are saying that when the Engine detects the MoveForward entry (defined as pressing the W and S keys) will call the method that matches the entry name, and the same principle is followed by the other entry. This is because we name the method as the entry, but this isn’t mandatory.

Next we check out the MoveForward implementation. This method receives a float as a parameter. This is the already known scale value registered in the Editor, so if the user press the W key, the method will receive a 1.0 value, and -1.0 if the S key was pressed. This method decides the rotation of the model and the direction vector in which it is oriented, and through the AddMovementInput method we make the character move in the resulting direction. Notice that the character moves upwards or backwards according to the value. AddMovementInput is APawn method that allows us to apply a movement to the Pawn in case that the character isn’t a physical body, like ours. In the MoveRight case, we apply the same logic but all of the calculations are based on the Y axis.

That’s all that we need for now. Compile and run the gamez. When the game starts, press the W, S, A, and D keys to control the character. Be careful not to fall off the edges of the platform ;). Unfortunately, we still have two problems with this movement. First of all, the character doesn’t rotate in the direction of the movement. Second, when the character is moving through the scene, it isn’t playing the walk animation. Let’s fix these two problems. To solve the rotation problem, open HeroCharacter.cpp and modify the constructor so that it looks like the following:

AHeroCharacter::AHeroCharacter(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{
    //This property by default has true value for the character
    //But in our displacement model we don’t want that the character rotates based in the controller rotation.
    bUseControllerRotationYaw = false;
    
    // CharacterMovement component configuration
    
     //This way we enable that the character rotates in the movement direction when the movement starts
    CharacterMovement->bOrientRotationToMovement = true;
    
    //Rotation factor to the previous property
    CharacterMovement->RotationRate = FRotator(0.0f, 540.0f, 0.0f);
    
    //We decrease the MaxWalkSpeed default value so the character walks slowly.
    CharacterMovement->MaxWalkSpeed = 400.0f;
}

Do you remember that the character has a CharacterMovement? We modified some values to change the default behavior of the character. I recommend you review the HeroCharacterBlueprint in the Editor to check all the properties that the CharacterMovement contains. Play around with them to see all that can be changed regarding the movement of the character.

Adding walk animation to the character

Now let’s focus on the last problem we have to solve. We need to make the character play the idle animation when he stays in rest, like it is now, but when the character is walking it should play the walk animation. In order to achieve this, we will see one of the two mechanisms that Unreal provide us to ease the transition between animations – the Blend Space.

Blend Space is the Animation Blueprint node that allows us to do blending between animations based in entry values. Unreal provides two types of Blend Space: the Blend Space used for several entries and the Blend Space 1D only for one entry. For this simple example, we will use the second one given that we only need one entry – the displacement velocity.

Once again open the Editor. Inside the Animations folder in the Content Browser, right click and select Animations/BlendSpace1D, name it IdleWalkBlendSpace1D, then double click it to open the respective Editor. We want to define the blending of the two animations using the value of the velocity variable. In the property panel of IdleWalkBlendSpace1D, in the X Axis Label, write Speed (this is only a reference, it could be any other word that represents the value that we have in mind to change from one animation to the other). In the range field, set 0 to 100. Now notice that at the bottom, there is a space with something that seems a graphic axis. From the Asset Browser, drag the idle animation and place it at the start of the x axis. Do the same for the walk animation but place it at the end of the axis. Done, now move the cursor over the axis and notice how in the Preview panel, the animation changes smoothly between the two animations by itself. Save and close the editor.

Setting the IdleWalkBlendSpace1D

Setting the IdleWalkBlendSpace1D

Now let’s modify the HeroAnimBlueprint so we can change the state machine for the behavior of the idle node (if you want to you can rename it to Idle/Walk). Now we will use this node to handle the two state. Enter to edit it, delete the idle node that we’re using and add the IdleWalkBlendSpace1D that we’ve created. This node, unlike the other, has an input port named Speed (the name we used when we created it), so in order for this to work we need to supply a value. There is an icon with a +V from Variable. This will allow us to add a new variable to the graphic. Click it and named it speed, drag it to the workspace and when it asks you Set/Get, select Get. Lastly, connect Speed to IdleWalkBlendSpace1D and this to Final Animation Pose.

imagen_14

We have to define, in the EventGraph, how we will provide the speed value to the idle/walk node. We will implement an algorithm that, in each loop of the animation, will get the Pawn (our character) after the call to the GetVelocity method that returns the displacement vector from the character in a given moment. Once we have the velocity, we calculate the distance of the vector and this will be our speed value. We will do all of this in HeroAnimBlueprint/EventGraph.

We’ve already seen the visual scripting in the Blueprint Editor so this will be a good time to reiterate upon how it works. It’s worth pointing out that we can also do this by code. But in the case, for controlling the logic of the animation behavior, I strongly recommend you to use the Blueprint because the preview tool allows you to easily check the changes and the final result. Also, all the animation mechanisms will be in a single place.

Open the HeroAnimBlueprint/EventGraph, then add and connect the nodes as in the next image. I won’t repeat how to do this step by step because detailed this earlier.

HeroAnimBlueprint/EventGraph algorithm contains the logic to set speed variable value used inside the state machine of the character to change between the idle and walk animations.

HeroAnimBlueprint/EventGraph algorithm contains the logic to set the speed variable value used inside the state machine of the character to change between the idle and walk animations.

Okay, now we’re really done. Compile, save the blueprint and click play to see the game. Pretty cool!!! Right, we have a character smoothly moving through the scene using the walk animation when it’s walking and the idle animation when it’s at rest☺.

Conclusion

We’ve finished this first tutorial: Introduction to Unreal Engine 4. In the next tutorial, we will modify the camera, the game controls and we will restrict the character movement in order to create a side-scroller style game. We will also add some more logic to the game, place some coins in the scene, and have our character collect all the staged coins in a given time in order to win or otherwise lose and start over. Meanwhile, please leave me your comments :). Also, you can follow me in Twitter (@nan2cc) to stay tuned for the next tutorials.

Fernando Castillo Coello
Follow me

Fernando Castillo Coello

Gameplay Programmer at GameOlic
I've been into games development with Unreal Engine since 2014 and want to share with you some of the tips and tricks that I learned during my journey.
Fernando Castillo Coello
Follow me

4 pensamientos en “Getting Started with Game Development using Unreal Engine 4

  1. Pingback: New Year’s Eve!~ So much UE4 >.< | The Forge

  2. Pingback: Unreal Engine 4 Tutorials and Info – IN YOUR LEGENDS

Responder a Shawn Cancelar respuesta

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>