Archivo de la etiqueta: game development

Making a 3D side-scroller game in UE4


Let’s start summing up what we did in the previous tutorial. We started our series with a general introduction to Unreal Engine 4 through a project which explores some of the basic concepts of the engine. We saw the framework’s class hierarchy, the visual scripting, the character animation settings, and we defined a fixed camera as a temporary solution in our game, among other things. If you haven’t already read the previous tutorial, I strongly suggest you do before continuing with this one.

In this tutorial, we will create the base to our 3D side-scroller game’s style. Currently my team and I are working on an automatic Runner, 2D side-scroller for IOS and Android. You can follow us on our Facebook page to keep up with our work in progress and to know when it will release. If you like this kind of game, I can assure you that you will love ours ;).

As I already said, in this tutorial we will configure our game camera to achieve a side-scroller view. We will also add some coins to our scene and use simple collision mechanism that will allow the character to collect the coins. We will “teach” our character to run and jump :). We will also see some variable and function macros for the integration between the C++ code and the Editor… and so much more. Are you ready?!… Well let’s get started!!

Setting the level from the editor

Let’s start by making a small change to the current level through the editor to match the style of game that we want. The base to a side-scroller game is to have the camera parallel to the main character and to have the camera a certain distance away from the character on the y axis. The character moves only in two directions – upward and downward when he jumps, and left/right when he walks.

Open in the Editor the UE4Demo project that we used in the last tutorial and delete the visible objects that we won’t use (the chairs, the table, the statue, etc.), leaving only the floor object. After that, modify this object using the transformation and escalate tools situated in the upper-right corner of the viewport. Then create copies of the object, modify them indistinctly and spread them through the level. Make sure to leave the ‘Actor Play Start’ on one of the platforms, to avoid that the character free fall into abyss. This is how I did it (use your imagination to achieve a better result than mine :).

Modified level in the Editor to match our game style

Modified level in the Editor to match our game style


As you will notice, when the game runs, it shows a red alert which says: LIGHTING NEEDS TO BE REBUILT. This alert has to do with the fact that we change the level geometry and the engine needs to rebuild the light so the illumination and shadows fit the new geometry. You can rebuild the lights selecting the Toolbar/Build/Build Lighting Only option. Run again and you will notice that everything goes back to normal.

For now we have a very basic level but enough to implement and test all the things that we have planned to do.

Configuring the camera for a side-scroller game.

At this point, it’s important to clarify that UE4 has a default template to build this style of game. In fact, we will use practically the same elements that this template uses but the idea of this tutorial is to do it from scratch to understand the basic concepts of the game style.

First we will change the game camera. In the last tutorial, we configured a simple fixed camera that served the purpose of introducing us both into the visual scripting (Blueprint Editor) and the C++ code. We will no longer use this camera so go ahead and delete the current implementation of the camera both in code and in the Blueprint Editor. If you still have the code implementation, comment out the lines inside the Begin Play method. In the Blueprint you may delete all the nodes or, if you want to keep the references, delete the connection leaving the BeginPlay node. By deleting this connection, we break the camera algorithm because the execution doesn’t continue when the BeginPlay event is executed but we still hold the rest of the connections and references.

Let’s configure a new camera’s style, this time through code in our Character’s class. Always take into account that you can also do it through the Editor. Remember that we have a Blueprint class that inherits our HeroCharacter class. A good way to practice will be for you to adventure by yourself once we do it by code to do the same in the Editor by modifying the HeroCharacterBlueprint.

Open the HeroCharacter class and add the next declarations after the GENERATED_UCLASS_BODY() macro:

/** Spring arm to fix the camera to the Character to match the side-scroller style */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
TSubobjectPtr<USpringArmComponent> SpringArm;
/** Game camera, is attached to the arm’s socket to achieve the side-scroller’s camera style */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
TSubobjectPtr<UCameraComponent> SideViewCamera;

We add two class variables to our HeroCharacter, but I’m sure that the thing that caught your attention was the UPROPERTY macro included for each variable. This way we define whether or not we want to use these attributes in the Editor and what options we have to work with them. As we saw in the previous tutorial, one of the coolest things about UE4 is the seamless integration between the code and the editor and this macro is one of the powerful utilities to achieve it. Next, let’s look at some of this macro’s parameters:

VisibleAnywhere: Defines if this property will be visible in the Editor’s property panel.

BlueprintReadOnly: Defines if this property could be read from VisualScript in the Blueprint, but it can’t be modified.

Category: Allow to specify a category name under the properties will be listed in the Editor.

You can find a detailed reference of all of the configurable parameters to the UPROPERTY macro in the Runtime/CoreUObject/Public/UObject/ObjectBase.h inside the UP namespace. If you click over a category while pressing the cmd key in MACOS, or click one while holding ctrl in Windows, you will be taken to the specific reference for that macro.
After we implemented the constructor where we initialized these variables, go to the Editor to check the result of defining the attributes with this macro.

These two class attributes just created in HeroCharacter are of a data type we haven’t used before. The first one is USpringArmComponent that we named SpringArm. Notice that we used the parametrized TSubobjectPtr class to define it. This way we can use the CreateDefaultSubobject method of the PCIP object received in the constructor to create an instance of any data type, which we will in a second. The USpringArmComponent allows us to fix a component to its parent in a fixed distance. We will use this component to fix the game’s camera with a certain distance from the character.

We will also create the class attribute SideViewCamera of UCameraComponent data type. The class name is quite descriptive. This attribute is our game camera :).

Next we will initialize this variable in the class constructor. Open the HeroCharacter.cpp and add the following code block:

//Initializing the USpringArmComponent attribute
SpringArm = PCIP.CreateDefaultSubobject<USpringArmComponent>(this, TEXT("CameraBoom"));
//Adding the springArm to the Character's RootComponent (the collision capsule)
//bAbsoluteRotation allows us to define if this support will rotate with the player or will stay fixed.
//In our case we don't want it to rotate with the character.
SpringArm->bAbsoluteRotation = true;
//The distance between the arm and its target. This value defines the distance between the character and the camera.
//Try out different values to see the outcome.
SpringArm->TargetArmLength = 500.f;
//Socket Offset.
//Socket is an anchor point to other components.
//For instance, in the character case we can define the socket in the character's hand
//this way we can add another component(for example a gun).
//But in our case we will add a camera to our SpringArm
SpringArm->SocketOffset = FVector(0.f,0.f,75.f);
//The relative rotation of the arm regard to its parent.
//We want the camera rotated 180 degrees in the Y axis in order to be situated parallel to the character, at the same level.
//This way we achieve the classic side-scroller camera's style.
SpringArm->RelativeRotation = FRotator(0.f, 180.f, 0.f);
// Creating the UCameraComponent instance.
SideViewCamera = PCIP.CreateDefaultSubobject<UCameraComponent>(this, TEXT("SideViewCamera"));
//The AttachTo method allow us to add an object to another in a given socket. It receives two parameters,
//the first one, the object where we will be anchored (the springArm) and the second the socket's name where we will be anchored.
//USpringArmComponent's SocketName returns the name of the components socket.
SideViewCamera->AttachTo(SpringArm, USpringArmComponent::SocketName);

Pay attention to each line comments so you can understand what each stands for. Overall, we create and configure the USpringArmComponent’s object and then we add it to the Character. Next, we create and configure the UCameraComponent’s object (the game camera) and add it to the USpringArmComponent to fix it to a given distance from the Character. Notice that we create the instances with the received reference in the constructor class using PCIP.CreateDefaultSubobject.

Ready, build and play the game. Now you have the game view in the side-scroller style :). Try to move in the level just created to see how the camera follows your every moment, always at a fixed distance.

New game view configuration to match the side-scroller camera's style

New game view configuration to match the side-scroller camera’s style


Don’t close the editor. Let’s focus in HeroCharacterBlueprint. In the last tutorial, we created this blueprint in the Character folder. Open it and activate the Components mode (upper-right corner). Notice that now in the Character’s Components panel we have a new object: the SpringArm and it contains a child the SideViewCamera. Check out all the properties defined by code. You can also check all the default properties values, change the values, and check out the different outcomes.

To test the parameters effect of the UPROPERTY macro in practice, go back to the code and delete the VisibleAnywhere parameter set in the property and build again. When you open the HeroCharacterBlueprint in the editor, in spite of seeing the components, we can’t see the properties values in the details panel when we select them.

Modifying the game controls for a side-scroller’s game.

So far we have set the camera’s style but I’m sure you noticed that the game controls don’t fit our game’s style, given that the character can move both in X and Y axis which is very unusual in a side-scroller game. Therefore we’ll change the game controls a bit to adjust them to the side-scroller style. We will also add two new actions and controllers to our character: run and jump.

I assume that after the last tutorial you have a couple of ideas of how to add these actions. In the Editor, select Edit/Project Settings/Input and leave only the MoveRight entry. Now let’s add another input type the ActionBinding. These entries, unlike the AxisBinding entries, are used to execute specific actions e.g. to jump or open a door. Create a new entry of this data type and name it Jump. Select the space bar as the key control. If you look closely you will notice that we can also define that the action gets executed when two keys are pressed simultaneously. In this case, will only use the space bar to jump.

New configuration of the game's controls. Adding jump control.

New configuration of the game’s controls. Adding jump control.


Now let’s code. First of all, we no longer need the MoveForward method of the HeroCharacter class. Delete the method statement in the .h and the implementation in the .cpp. Also, in the SetupPlayerInputComponent method, delete the MoveForward BindAxis. Lastly, we have to modify the MoveRight implementation given that at the moment when the entry gets called we rotate the character position, now we want that the character to move forward and backward respectively. Modify the MoveForward as the code below:

*  Gets called when the MoveForward entry is detected (When the user press the A or D keys).
*  @param Value Value is equal to 1 when the D is pressed and -1 when A is.
void AHeroCharacter::MoveRight(float Value)
if ( (Controller != NULL) && (Value != 0.0f) )
        // Adds a new movement to the right or left according to the Value value.
        AddMovementInput(FVector(0.f,-1.f,0.f), Value);

Now this method is much simpler and I hope it’s easier to understand what it does. Anyway, I will explain step by step what we just did. We apply a movement vector that affects only the y axis of the vector’s value. So when the user presses the D key, the character will move forward (to the right) and when the A key is pressed, the character will move backward, meaning to the left side.

Now we have to implement the method that will get called to execute the jump action when the user presses the space bar. It’s very simple. Just add the next line to the SetupPlayerInputComponent method:

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

Notice one thing, the method that gets called is the ACharacter::Jump. Jump is a method implemented in our base class, not in our own class HeroCharacter. This method already has all that we need to make the character jump. It’s really amazing how much help the framework provides us with :).

Go ahead build and play the game. Press the A and D keys to see how the character moves correctly on the scene, and how when you press the W and S keys, nothing happens. Hit the space bar and you will see how our character now also jumps :) … but something is still missing. Yes the character is jumping but visually is playing the walk animation. Next thing we need to do is add the jump animation.

Setting the jump animations for the character

Since the last tutorial, we have the main character resources that supposedly our design team have us, among them we have three FBX animations to jump: the Jump_End.FBX, Jump_Loop.FBX, Jump_Start.FBX and the Run.FBX file. Import them in the Animation folder. You can inspect them in the Persona Editor.

I’m sure that the fact that we have three different animations for the jump caught your attention, and you ask yourself, “Why??”. I will give you the answer right away but first let me share a personal experience with you involving this aspect: When we start the development of our current project, you can take a look in here :)). We struggle with this problem.
In our game, the character jumps at different heights. For instance, it can do a small jump to avoid a box or a long jump from a cliff and stays longer in the air. The problem is that in the long jump case we play the jump animation when the action is started with a duration and might end while the character is still in the air falling in the last frame of the jump animation until it touches the ground where the transition will continue normally. That’s the reason why in many cases, it’s necessary to divide the jump animation in three pieces, we have the start jumping action then we have a loop animation that is played while the character is falling and finally the animation when the character touches the ground. This is how we achieve the whole jump animation cycle independently of the height.

Let’s configure it in the character animation blueprint. As we saw in the last tutorial, we use a state machine for the animation system that allows us to separate the different states that our character supports and set an animation for each state. Currently the state machine of our character is very simple, containing only the Idle state and the Walking state. Let’s add the jumping states.

Inside the HeroAnimBlueprint/AnimGraph, enter the state machine, drag the cursor from the Idle/Walk node to create a new node, and name it JumpStart. Repeat the procedure twice using the last created node to create the JumpLoop node and finally the JumpEnd. At the end, connect the JumpEnd state to Idle/Walk to close the cycle. It should look like this:

New Character state machine, with the jumping states added

New Character state machine, with the jumping states added


We have just defined three new states to our character and the order in which they would be reached. In other words, the character could be in rest or running and can change to the JumpStart state (jump starts). From the JumpStart state, he can reach the JumpLoop (loop cycle) and then the JumpEnd state. Lastly, he could go to the Idle/Walk state. Notice the directional arrows between the states. These are the connections that define the origin and destination states. If you jump you will notice the four states and the blending between them.

Each state has an icon over the transition arrow. This icon represents the condition that triggers the transition between the states. We have to define this condition using the visual scripting in the Blueprint Editor. The first case is when the character is in the Idle/Walk state and starts the jump action. The condition to pass to this state will be BOOL variable that will store if the character is in the air or not. When the character changes the state such that it is in the air, we will change to the JumpStart state.

Double click in the transition icon to enter in its edition mode. By default we have a Result node with the “Can Enter Transition” description. This node expects a bool parameter that the state machine will use to decide if the state transition takes place. Create and add a new variable like we did in the last tutorial but this time use bool as data type. Name it IsInAir or any name that you prefer but it must be something meaningful. Add it to the blueprint in GET mode and finally connect this node output port to the input port of the Result node. So if the IsInAir variable has a true value, the transition will execute and the character will pass to the JumpStart state.

VisualScript of the transition between the Idle/Walk and JumpStart

VisualScript of the transition between the Idle/Walk and JumpStart


Save and exit the edition mode of the transition between the Idle/Walk and JumpStart and enter the edition mode of the JumpStart node to define which animation will be played in this case. Drag the JumpStart animation from the resources folder into the blueprint and connect it to the final node. The JumpStart and JumpEnd animations will be played only once which is different to what we did in the last tutorial where the Idle and walk animations are played in a loop. The idea is to start playing the JumpStart then pass to the JumpLoop that as its name suggest plays in a loop and finally play the JumpEnd animation only once. So select the JumpStart animation and in the property panel, uncheck the Loop option. Do the same for the JumpEnd animation.

VisualScript of JumpStart node

VisualScript of JumpStart node


Now we have to define the condition to pass from the JumpStart to the JumpLoop animation. For this task we will use a new node. We need to be able to detect when the JumpStart animation is about to end to know when to start playing the loop animation. Double click in the transition icon between JumpStart and JumpLoop. Once again we meet the Result node that we’re about to use but first we need to do an algorithm to define when the animation is near to end.

Let’s add a new node of the Time Remaining (Ratio) type to the Jump_Start Asset. This node informs us of how much time remains before the animation ends. Let’s add another node < float type, we will use it to know if an A parameter is smaller than a B one. Connect the output port of the TimeRemaining node to the upper input port of the comparison. For the second input port, we will use a manual value, in this case 0.1. Now,when the TimeRemaining is less than 0.1 (the animation is about to end), we transition to the JumpLoop state. In order to complete the transition setup, we still have to connect the comparison node output to the Result node. It should look like this: [caption id="" align="alignnone" width="630"]VisualScript of the transition between JumpStart and JumpLoop animationsVisualScript of the transition between JumpStart and JumpLoop animations[/caption]


Summing up, we periodically check if the StartJump animation is about to end by checking if the remaining time is less than 0.1. When this condition is fulfilled, the transition is executed.

Save and exit the transition’s edition mode and enter the state JumpLoop edition mode. Add the JumpLoop animation and connect it to the Result. Unlike with the JumpStart animation, with the JumpLoop animation, we need to play it in a loop because this is the one that plays while the character is falling, so check that the loop option is checked.

JumpLoop's node VisualScript

JumpLoop’s node VisualScript.


Let’s configure the last transition between the JumpLoop and JumpEnd nodes. JumpEnd, as its name suggests, is the animation played when the jump ends. The condition to transition to this state is that the character is close to the floor (it’s no longer in the air). That’s exactly what the isInAir variable represents. Double click on the transition icon between JumpLoop and JumpEnd and add the isInAir variable as GET. The problem is that we need to know when the character isn’t in the air so we need to use the isInAir negation, so we will add a NOT node type to the blueprint. This node type returns the input’s negation. Connect the NOT node to the isInAir node and this to the Result. Now, as soon as the character hits the floor, the character will transition to the JumpEnd state.

VisualScript of transition between JumpLoop and JumpEnd

VisualScript of transition between JumpLoop and JumpEnd.


Exit the transition’s edition mode and enter in the JumpEnd edition mode. Drag and connect to the Final Pose the JumpEnd animation and uncheck the loop option.

JumpEnd's node VisualScript

JumpEnd’s node VisualScript


Finally, we have to define the condition for when to transition back to the Idle/Walk state coming from the JumpEnd state. This animation represents the character already on the floor but still recovering from the fall. We need to wait until the JumpEnd animation is about to end to change to the initial state (Idle/Walk). Basically, we will repeat the steps we use in the transition between the JumpStart and JumpLoop. I hope you are able to do it by yourself… 😉 it should look like this:

VisualScript of transition between JumpEnd and Idle/Walk

VisualScript of transition between JumpEnd and Idle/Walk


Now we have completed the character state machine, but a small detail is still missing. We need to set the IsInAir variable value like we did earlier with the Speed variable.

Close the AnimGraph Editor and open the EventGraph. Add a GetMovementComponent node and connect the TryGetPawnOwner node that we created in our last tutorial to the input port of the GetMovementComponent node. Add another node and name it IsFalling and connect its output port of GetMovementComponent to the new node’s input port. Add the IsInAir variable in SET mode and connect the IsFalling output to the IsInAir input. Finally, connect the blank output port of the SET Speed to the SET IsInAir input for the algorithm continuity.

HeroAnimBlueprint's EventGraph modify it to set the IsInAir variable value when the character is in the air

HeroAnimBlueprint’s EventGraph modified to set the IsInAir variable value when the character is in the air


If you have read the previous tutorial, I’m sure you won’t have any problem understanding what we just did. We got the character’s MovementComponent, which contains an IsFalling method that returns a bool value denoting if the character is in the air or not. This IsFalling method is the one we will be using to set our IsInAir variable. Now we have the state machine for our character. Build the AnimationBlueprint and run the game. Press the space bar … now our hero jumps too :).

Character jumping with proper animation

Character jumping with proper animation


Implementing character’s running mechanism!!

Now our character knows how to walk, rest and jump, but a classic feature in side-scroller games is the ability to run to get more momentum and jump higher and further. Who doesn’t remember in one of Super Mario latest level the huge hole that can only be jumped with a great momentum, do you :)… So the next thing we will do is to add this skill to our character. Let’s implement it so that when the character is walking and the Shift key is pressed, the character will run.

First of all, open the editor and in the controls sections, add a new ActionBinding entry, name it Run and select the LeftShift key. Close the editor and open the HeroCharacter.cpp inside the SetupPlayerInputComponent method and add the following two lines:

//The Run entry is detected, when the Shift key is pressed we set that the ToggleRunState method should be call.
InputComponent->BindAction("Run", IE_Pressed, this, &AHeroCharacter::ToggleRunState);
//The Run entry is detected, when the Shift key is released we set that the ToggleRunState method should be call.
InputComponent->BindAction("Run", IE_Released, this, &AHeroCharacter::ToggleRunState);

Notice a tiny detail in this code. We are setting the BindAction for the Run entry twice and passing the same ToggleRunState method (that we will soon implement). The difference between the calls is that the second parameter specifies when the method gets called. The first case, IE_Pressed is fulfilled when the Shift key is pressed and IE_Release when it’s released. What we want to achieve is that when the key is pressed, the character runs and when the key is released, the character stops running and continues walking. Very similar to the Super Mario logic for the big jump!! :).

Now let’s implement the ToggleRunState method. Add the method’s declaration to the .h file:

* Gets call when the engine detects the Run entry
* Change to the character run state.
void ToggleRunState();

Go to the .cpp and add the following lines to the implementation:

* Gets call when the engine detects the Run entry
* Change to the character run state.
void AHeroCharacter::ToggleRunState()
//If the CharacterMovement's MaxWalkSpeed attribute is 400.f we increase it to 900.f to achieve that the character will  move faster.
//Otherwise we set it to 400 again so the character move in the walk speed range.
    if(CharacterMovement->MaxWalkSpeed == 400.0f)
        CharacterMovement->MaxWalkSpeed = 900.0f;
        CharacterMovement->MaxWalkSpeed = 400.0f;

By default, the movement speed value is 400. When the shift key is pressed, we change the MaxWalkSpeed to 900, which causes the character to move faster. When the shift key is then released, the method is called again and we set the value back to 400, decreasing the movement speed.

If you want to test your knowledge, you can implement the run mechanism in the HeroCharacter’s Blueprint. If you accept thus challenge, remember first to delete the C++ code. It should looks like this:

Blueprint version of the run mechanism

Blueprint version of the run mechanism


I personally prefer to keep all the character’s logic in code, but this exercise may serve as practice to increase your skills in the Blueprint Editor, something that’s new for much of us and I’m sure caught your attention :). I also recommend to expose the max and min values of the MaxWalkSpeed so it can be modifiable from the Editor and to avoid going to the code to change its values. Remember, in order to make variable values modifiable via the editor, you have to use the UPROPERTY macro, but this time I won’t show you how I did it so you must check how we did it previously and use your imagination. I’m sure you can do it 😉

Build and play the game. Let’s try it out. While you’re walking, press the shift key and you will see how the character moves much faster. We’re not quite finished yet because the character still uses the walk animation while running so it looks weird.

Adding the run animation to the character

Let’s add another animation to our character – the run animation. We will use the Idle/Walk state created previously to add the run animation. We will also use the same node to blend between the animations. An amazing feature of this type of node is that we can add more than two animations. The idea is to modify it to set three control points: the first one at the start of the graph will use Idle animation, the second in the middle of the graph will use the Walk animation, and the third at the end of the graph for the Run animation.

Import Run.FBX from your resources, open the IdleWalkBlendSpace1D created in the last tutorial, change the X Axis Range property to 900 (the movement value of the character when it’s running), and click the Apply Parameter Changes. Now add the Idle animation at the start, the Walk animation in the middle, and the Run animation at the end. Make sure the Enable Preview BlendSpace option is checked and move the cursor over the graph to see the blend between the animations according to the speed value. Pretty cool and easy, ehhh???

New IdleWalkBlendSpace1D configuration for the Idle/Walk/Run state

New IdleWalkBlendSpace1D configuration for the Idle/Walk/Run state


Save, play the game and try to run. Now our character walks and runs perfectly.

Running character pressing the D+Shift keys

Running character pressing the D+Shift keys


Adding coins in the scene for the character collect.

We already have our character walking, running and jumping through the scene in a side-scroller style, but we need to add some purpose to the game because wandering around isn’t much fun. Let’s try to improve it a little by adding some coins in the scene for the character to collect, a common feature in this style of game. In next tutorials, we will see what our character wins with these coins.

First, we need a coin model. I’m sure you can find several StaticMesh that you can use as coins from the MarketPlace. I strongly recommend you take some time to visit the MarketPlace. I’m sure that you will find a lot of things that you will love and many of them are FREE!! :D.

Anyway, you can download the FBX of a very simple coin here :S Its not amazing but it works for this tutorial. Import the FBX file to the project (I created a Coin folder). In the importing window, you will notice that Unreal detects that this is a StaticMesh. Expand the advanced options and select the materials and texture options. This way, we’re also importing the model’s material. That is also extremely simple.

Now with the resource imported, let’s create the C++ class that encapsulates all the coin logic. Create a new class in the Editor and named it Coin. This class will inherit from Actor. Select Yes when the Editor asks you if you want to open the class in the IDE. Modify the .h file so it looks like the following:

/** Represents a coins. The character can collect them by colliding with them. */
class ACoin : public AActor
     * USphereComponent is sphere shape component generally used to detect simple collisions
     * This will be the root component of the coin and with it we will detect the collisions between the character and the coins.
     UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Coin)
    TSubobjectPtr<USphereComponent> BaseCollisionComponent;
    /** Coin's StaticMesh, we used previously in the Character. We store the coin's StaticMesh instance. */
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Coin)
    TSubobjectPtr<UStaticMeshComponent> CoinMesh;
    /**  Boolean variable to enable/disable the coin */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Coin)
    bool bIsActive;

I recommend you pay attention to the code comments because I always point out which function has every line. Basically, we define the BaseCollisionComponent attribute to be the root component of our coin which we will use to detect collision. The other attribute is the UStaticMeshComponent which is used to define the StaticMesh that represents the coin in the level. The last one is the bIsActive we will used as a flag to disable the coin when the user collides with it.

Go to the .cpp file and modify the constructor to match the following code:

ACoin::ACoin(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
    //Create the USphereComponent instance.
    BaseCollisionComponent = PCIP.CreateDefaultSubobject<USphereComponent>(this, TEXT("BaseSphereComponent"));
    //Initialize the Actor's RootComponent with the USphereComponent.
    RootComponent = BaseCollisionComponent;
    //Create the UStaticMeshComponent instance
    CoinMesh = PCIP.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("CoinMesh"));
    //We add the UStaticMeshComponent as child of the root component
    //By default the coin will be active
    bIsActive = true;

We instantiate the USphereComponent as the coin’s root component. We also create the UStaticMeshComponent instance. We will soon configure it from the Editor and then added it to the RootComponent. Finally, we set the bIsActive variable to true because we want the coin to be active when it’s created.

Adding coins to the scene

Let’s create the Coin’s Blueprint as we did with the Character in the last tutorial. In the ContentBrowser, select the Coin folder, then right click and select the Blueprint option. Finally, set Coin as the base class and name it CoinBlueprint. As you will see, it contains the same components that we define in the USphereComponent constructor, for instance, the RootComponent and the UStaticMeshComponent. Unfold the CoinMesh and select the StaticMesh imported for the coin.

CoinBlueprint component's section. Adding the StaticMesh component

CoinBlueprint component’s section. Adding the StaticMesh component.


Now we will add some coins to the scene. Find the CoinBlueprint in the ContentBrowser and drag it into the level at the position where you want to place a coin. This must be a place reachable by the character. It’s important to remember that in this style of game, the character is placed on a fixed Y axis, so you must place the coins at the same Y value as the character in order for him to collide with the coins.

This is the simple level I made:

Level in edition mode with coins added.

Level in edition mode with coins added.


We added the coins to the level, but so far they don’t do anything. If you walk into the coins, nothing happens. Besides, the coins look very bad because they’re static. Let’s add some life to them.

Collision mechanism to collect the coins

At the moment, the character hits the coins but there isn’t any feedback. Let’s add the collision detection that, as its name suggests, will detect the collision between the character and the coins. We will have a “Collected coins” variable that we will increase when the character collides with a coin. We will create and call the OnCollected() method in the Coin class where we will disable the coin, delete it from the scene and print a log on the screen to debug the algorithm.

Open the HeroCharacter.h and add the following declarations:

    /** Character's amount of coins collected */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category=Coins)
    int32 CoinsCollected;

    /** It's called constantly in the character's Tick to check if its colliding with a coin */
    void CollectCoins();
     * Gets executed automatically by the engine every frame
     * @param DeltaSeconds the difference in seconds between the last and current frame.
    virtual void Tick(float DeltaSeconds) OVERRIDE;

Before we get deep in code, let’s theorise on the functionality that we will use. Every Actor in UE4 implement the Tick method. This method is called automatically by the engine every frame. If you are reading this tutorial, you are probably familiar with game development, at least with its theory. If so, you will know this method’s significance. Basically, all of the Actor’s algorithms that must run constantly will be called inside this method. The method receives a float as a parameter. This is the amount of time, in seconds, that has passed since the last tick/frame. This value is commonly used in a variety of tasks. For instance, it can be used as a multiplier when modifying the character’s position or rotation in order to achieve an execution depending on the framerate as to avoid gaps in case that the framerate decreases.

So we will call the CollectCoins method in the Tick method so it runs constantly. Internally, this method checks if a coin is inside the Character’s CapsuleComponent. If it is, that means that the character is colliding with that coin do we should trigger our collision mechanism.

Open the HeroCharacter.cpp file. At the end of the constructor implementation, add the CoinsCollected = 0 line. This causes the CoinsCollected variable to be set to zero when the character is create and is done because hasn’t collected any coins. Add the CollectCoins and Tick methods:

/** It's called constantly in the character's Tick method to check if is colliding with a coin */
void AHeroCharacter::CollectCoins()
    //AActors array to save temporary all the actors that are colliding with the character
TArray<AActor*> CollectedActors;
    //GetOverlappingActors method of the CapsuleComponent. This method returns all the actors colliding with the character in the array we pass as parameter.
    //All the objects that are currently inside the capsule.
    //We iterate through all the objects inside the CapsuleComponent.
    for(int32 i = 0; i < CollectedActors.Num(); i++)
        //We have to cast the array elements to ACoin because the array is declared as AActors.
        ACoin *Coin = Cast<ACoin>(CollectedActors[i]);
        //We make sure that the coin is active and that the Destroy method hasn't been called
        if(Coin != NULL && !Coin->IsPendingKill() && Coin->bIsActive)
            //We increase the coins collected amount.
            //Finally, we call the OnCollected method of the Coin class to execute all the collect coin logic.

* Gets executed automatically by the engine every frame
* @param DeltaSeconds the difference in seconds between the last and the current frame.
void AHeroCharacter::Tick(float DeltaSeconds)

    //In every update is called the CollectCoin to constantly check if it's colliding with a coin.

Take a minute to read every line’s comments to really understand the collision detection process. This is a very simple collision detection but it’s enough to understand how to work with it in UE4 :). It’s important to clarify that inside the CollectCoins method we have a reference to the ACoin class created by us. To avoid errors, we have to add #include “Coin.h” declaration at the top of the .cpp file below the #include “UE4Demo.h” line.

Only one small thing is left. If you try to build now you will get an error because when a collision is detected, the OnCollected method of the Coin class is called and we haven’t implemented this method yet. Let’s do that now:

Add the method’s declaration to the .h file and the implementation in the .cpp.

/** It's called when a collision is detected */
void ACoin::OnCollected()
    //To Debug we print a log on the screen
    GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, "Coin Collected !!");
    //We change to false the bIsActive flag
    bIsActive = false;
    //We call the Actor's Destroy method, to remove the coin from the scene

This method will be called when a collision is detected. First we use the AddActorLocalRotation method of the framework’s GEngine object. This method is very handy because it allows us to print messages in a specific colour at a certain amount of time on the screen. To debug our code in runtime is very useful. Here we print Coin Collected when the character collides with a coin. Besides that, we set the bIsActive variable as false and we remove the coin from the scene using the Actor’s Destroy method.

Build and run the game one more time. Now walk into a coin … Very nice!! When the character passes through a coin, the coin is removed from the scene. Internally, the amount of coins collected is increased (at the moment there isn’t any visual feedback regarding this value) and then we print the temporary Coin Collected¡! log to the screen.

“Debugging” the scene collisions

If you are good at paying attention to small details, I’m sure you will notice a small problem with this collision mechanism. Try to reach a coin slowly, you will notice that the collision occur before the character actually touches the coin. To find the problem, UE4 provides us with an amazing command that allows us to check the collision component of an actor at runtime. Run the game one more time and pay attention in the upper-right corner of the Editor. You’ll notice there is a text field that allows us to write commands. Write in the field: show COLLISION and press the Enter key. Immediately, the collision component appears over every actor .

Run time game with the show COLLISION command active to debug the Actor's collision component.

Run time game with the ‘show COLLISION’ command active to debug the Actor’s collision component.


Notice two things that could the cause the problem. First, the coin component is bigger than the coin itself. Second, the character’s capsule radius could be reduced. End the game execution and open the CoinBlueprint then select ROOT in the components mode. In the Details panel, search for the Shape section that holds the sphere radius. Change its value to 15 and check out the preview showing how the sphere surrounds the coin. Notice how this adjustment better fits the model. Save and try again. You will see how the collision detection has improved as now the character has to be very close to catch the coin.

Modifying the sphere component radius to adjust the collision detection

Modifying the sphere component radius to adjust the collision detection


You can do the same with the character’s capsule if you want to continue improving the collision mechanism. It’s important to mention that this value can be defined in the class constructor by code. Try to do it by yourself to practice.

Rotating coins on its own axis.

To add some life to the coins, we will rotate them on their own Y axis. Close the editor, open the Coin.h class and add the following lines:

    /** Coin rotation factor */
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Rotation")
    FRotator RotationRate;
    virtual void Tick(float DeltaTime) OVERRIDE;

We simply add the Tick method and a new RotationRate attribute of FRotator type. This is the rotation vector we will use to rotate the coin in every Tick call. Actually, there is no need to declare an attribute but in doing so, we gain the opportunity to configure the rotation factor in the editor, thanks to the UPROPERTY macro.

Go to Coin.cpp file. At the end of the constructor, add this two lines:

    //Initialize the coin rotation factor in each update
    RotationRate = FRotator(0.0f, 180.0f, 0.0f);
    //Enable the Tick method of this Actor
    PrimaryActorTick.bCanEverTick = true;

The first line is the rotation vector’s initialization. By default, the Tick method isn’t called automatically in an Actor inherited class such as our Coin class. To enable the call to the Tick method in this class, it’s necessary to set the PrimaryActorTick.bCanEverTick attribute as true.

Very well, now add the Tick method’s implementation:

void ACoin::Tick(float DeltaTime)

    //Adds a rotation factor to the coin in each Tick call
    AddActorLocalRotation(this->RotationRate * DeltaTime, false);

The code is very simple. Basically we add a rotation factor thanks to the AddActorLocalRotation, in each update.

Ready!! Build, run and test. Super nice, right!! The coins are constantly rotating in the scene, waiting to be caught :).

Implementing the coin logic in the Blueprint.

As I already mentioned in the last tutorial, the decision of whether to use the code or the Editor is up to the individual. I personally follow these two rules of thumb. 1. Implement all the related things only in one place (for maintenance purpose). In other words, don’t have half of the logic in code and the other half in the Blueprint. 2. If the Actor logic is very simple like it is for this coin, the ideal solution is to use the Blueprint. However, when the thing needed to be implemented is large and complex, I personally prefer to use C++.

You could have some practice implementing the coin logic in the Blueprint. Do you dare? It should look something like:

Coin VisualScript

Coin VisualScript


Notice that we implement what happens when the OnCollected method is called in the Blueprint. We still have to add in the method’s declaration, the UFUNCTION(BlueprintNativeEvent) macro, or the UFUNCTION(BlueprintImplementableEvent). Next I will explain both:

UFUNCTION(BlueprintImplementableEvent) is designed to be overridden by a blueprint. Do not provide a body for this function; the automatically generated code will include a thunk that calls ProcessEvent to execute the overridden body.

[UFUNCTION(BlueprintNativeEvent) macro]. This function is designed to be overridden by a blueprint, but also has a native implementation. Provide a body named [FunctionName]_Implementation instead of [FunctionName]; the automatically generated code will include a thunk that calls the implementation method when necessary.

For example, if you want to test the OnCollected method, the definition will be like this:

void OnCollected();

And the implementation should look like:

void ACoin::OnCollected_Implementation()
    //As Debug we print a log on the screen
    GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, "Coin Collected !!");
    //We change the bIsActive flag to false
    bIsActive = false;
    //We remove the coin from the scene with the Destroy method

The silver lining is that we can have our code implementation, but we can also override this implementation in the Blueprint … cool, right? UE4 stuffs!! :). Try the coin logic implemented in VisualScript in order to gain confidence in the Blueprint Editor, one of the wonders of UE4.


Well, I think it’s time to call it a day. In this second tutorial, we did several new things. Among them, we made a simple collision detection mechanism We implemented the Tick method. We added the run and jump animations to the character. We configured our game camera to the 3D Side-Scroller style. We saw some variables and macro class functions for the integration between the code and the Blueprint Editor, etc.

In next tutorial, we will continue to build our game. We will add a HUD so the user knows the number of coins collected, and the time available to achieve some goal. We will define the GameMode, the win and lose conditions and so much more ;).

I hope you found this tutorial useful. If you did, please leave me your comments and share this tutorial with the rest of your friends who are also passionate about game development with UE4. Till next time!!… Bye.

Cómo causar daño a un personaje en UE4 – Parte 2

En el tutorial pasado vimos una introducción al AnimComposite y el AnimMontage en Unreal Engine 4 y dejamos a nuestro personaje con las habilidades necesarias para dar puñetazos. En este tutorial vamos a usar esas habilidades para golpear a otro personaje, causándole daño hasta que su salud llegue a 0 y muera.

Este simple ejemplo nos permitirá ver varias cosas nuevas:

– Introducción a los mecanismo de colisión que nos brinda UE4
– El uso del MarketPlace.
– El uso del Construction Script en los blueprints
– Cómo aplicar daño a un personaje
– Introducción al trabajo con efectos de sonido en Unreal Engine 4
– Cómo reproducir un AnimSequence directamente desde código
– Como eliminar un Actor del nivel cuando ya no se va a usar más

Y muchas cosas más 😉 … así que, manos a la obra !!

Introducción a los mecanismos de colisión en Unreal Engine 4

En el segundo tutorial vimos un ejemplo simple del trabajo con las colisiones entre dos objetos, cuando implementamos la funcionalidad para que el personaje pudiera recolectar las monedas dispersas por el terreo. Vamos en este tutorial a profundizar un poco en la teoría detrás de las colisiones en UE4.

Unreal Engine 4 tiene un potente y flexible mecanismo para el manejo de colisiones entre los elementos del juego. Cada objeto que puede colisionar con otro es de un “Object Type“ y se le define cómo responderá a la colisión con los otros Object Types de tres formas distintas: si lo Ignorará, si se superpondrán o si lo bloqueará. Los Object Types existentes son:

WorldStatic: Los Volúmenes existentes en el juego, y los objetos estáticos del nivel, por ejemplo: Una piedra o una pared deben ser WorldStatic

WorldDynamic: Los Actores dinámicos (los que se mueven) a parte a los Pawn, PhysicsBodies y Vehicles (que son Objet Type específicos). Serían por ejemplo, una plataforma que se mueve de un lado a otro, un elevador, etc.

Pawn: Los personajes, estos ya los conoces 😉

PhysicsBody: Los objetos físicos. El trabajo con objetos físicos los veremos en próximos tutoriales. Básicamente son objetos que se les puede definir para que se comporten físicamente real. Por ejemplo, que los afecta la gravedad, su masa, fuerzas o impulsos que se les aplica, etc. Los objetos de este tipo en el nivel deben tener como Object Type, PhysicsBody.

Vehicle: Este es bastante claro, no ? :) .

Destructible: Actores destructibles. Estos los veremos también en próximos tutoriales y de seguro te va a encantar jugar un poco con ellos. Básicamente son objetos que los podemos configurar para que se fraccionen y se rompan cuando reciban un impacto, un efecto genial y que siempre gusta mucho.

Bien, ya sabemos los distintos Object Type que nos da UE4, ahora vamos a investigar un poco como está configurado por defecto nuestro personaje protagónico para responder a las colisiones. Abre el Blueprint del personaje, selecciona el modo Components y selecciona el componente [ROOT]CapsuleComponent. En el panel de detalles muévete hasta la sección Collision y despliega la propiedad Collision Presets.

Blueprint del personaje en el modo Components donde se muestra la configuración de Collision del [ROOT] CapsuleComponent

Blueprint del personaje en el modo Components donde se muestra la configuración de Collision del [ROOT] CapsuleComponent


Desde esta sección podemos configurar el Object Type de este objeto y cómo reaccionará a las colisiones con los otros elementos del juego. Fíjate en la propiedad Collision Presets, en este caso tiene seleccionado Pawn. El UE4 por defecto nos trae un grupo de configuraciones predefinidas que son comunes en los juegos y que podemos seleccionar, y así no tenemos que configurar siempre manualmente como reaccionará este objeto con los otros con los que colisione. Si expandes esta sección verás que todas las propiedades están bloqueadas y con una configuración predefinida, prueba variar la selección de Collision Presets a otro que no sea Pawn, notarás que cambia la configuración. Por supuesto, siempre podemos seleccionar Custom … y settear la configuración que queramos específicamente para cada Object Type.

La configuración de colisión que tiene el CapsuleComponent del personaje, predefinida por el Preset Pawn es la siguiente:

Primero tenemos la propiedad Collision Enabled en la que se pueden seleccionar tres posibles valores:

No Collision: Cero colisión, son ignoradas totalmente las colisiones en las que interviene este objeto.
No Physics Collision: Las colisiones de este objeto solo se tienen en cuenta para raycasts y overlaps (los veremos más adelante)
Collision Enabled: Para responder a ambos tipos de colisiones: con simulación física y sin ella.

Debajo tenemos el Object Type para definirle a este elemento. En este caso es Pawn.

A continuación tenemos una especie de tabla. Las filas son cada uno de los Object Type y cada columna representa un tipo de Collision Response que tenemos para reaccionar a una colisión, estos son:

Ignore: Ignorará completamente la colisión. Lo que quiere decir que para el Object Type que se le marque Ignore, cuando este objeto colisione con él, ignorará por completo esto y lo traspasará.

Overlap: Overlap es igual a Ignore, o sea, los objetos se traspasan, pero este tiene una particularidad. Si te fijas, al inicio de la sección Collision tenemos dos atributos a marcar. Simulation Generate Hit Event y Generate Overlap Event. Si le marcamos para un determinado Object Type que maneja la colisión con Overlap estos se traspasarán, pero si la opción Generate Overlap Event está en true, en el momento de la colisión se generará un evento que podemos intervenir desde el Blueprint o C++ y ejecutar una acción determinada. Veremos un uso de esto más adelante. Además de la opción Generate Overlap Events tenemos la propiedad Simulation Generate Hit Events. Este check es semejante al otro pero lo usamos cuando el objeto es físico. Habilita para que se generen eventos de tipo Hit cuando el objeto físico colisiona con otro. Veremos su utilidad en próximos tutoriales.

Block: Con el objeto que se defina para que responda a la colisión con Block no podrá ser atravesado. En el caso de la cápsula de colisión del Pawn verás que para todos los Object Type el Collision Response está en Block, para evitar que el personaje atraviese las cosas.

Por último, un detalle importante, fíjate que las filas están separadas en dos bloques Trace Response y Object Response. El primero nos permite definir como reaccionará el objeto a las colisiones con los Traces, estos son básicamente rayos invisibles que podemos usar para determinar si algún objeto colisiona con ese rayo y tiene montón de utilidades. Veremos uso de estos en próximos tutoriales.

Te recomiendo que le dediques un tiempo a revisar la configuración de colisión para cada uno de los Collision Presets y además la configuración de colisión para cada uno de los componentes del personaje, otra configuración importante a tener en cuenta y entender es la del Mesh del personaje que usa como Collision Presets: CharacterMesh

Configuración de las propiedades de Collision para el Mesh del personaje.

Configuración de las propiedades de Collision para el Mesh del personaje.


Muy bien, ya con esta teoría de nuestro lado, podemos pasar a implementar la funcionalidad para poder golpear al lanzar un puñetazo. La lógica detrás de esto sería: detectar cuando el puño colisiona con el otro personaje y en ese momento implementar lo necesario para reaccionar al golpe. Vamos a agregar al nivel otro personaje que nos servirá como monigote para practicar nuestros golpes.

Con los recursos que tenemos ahora mismo, poco podemos hacer, pero aquí viene otro de los enormes regalos que tenemos al usar Unreal Engine: El Marketplace !!. El equipo de Epic, por si fuera poco el poner este fenomenal motor en nuestras manos, también nos brinda acceso al MarketPlace, la zona en donde podrás encontrar una enorme cantidad de recursos para tus proyectos, tus prototipos para aprender, etc. Es un lugar que al menos todas las semanas deberías darle un recorrido para ver que te trae de nuevo.

Introducción al Marketplace

Para usar el Marketplace tienes que tener tu subscripción válida y el Unreal Launcher, que si no lo tienes, lo puedes descargar haciendo clic en el editor en la barra superior en el botón MarketPlace:


Una vez que abras el Unreal Launcher tendrás la pantalla de login. Pon tu usuario y password y … “Bienvenido al paraíso“ !! :)

Captura del Marketplace

Captura del Marketplace


Tómate unos minutos y revísalo, veras el montón de cosas que encontrarás, de seguro lo querrás bajar todo :) .. . . sí, es verdad, no todo es gratis, de hecho, la mayoría de las cosas son de pago, pero vamos !! mira el precio y compáralo con todo el trabajo que te ahorrarás, la ventaja es enorme !!. De cualquier forma, no te preocupes, lo que vamos a necesitar en nuestros tutoriales es gratis :). Busca aquí el Animation Pack y descárgalo (está marcado en rojo en la imagen anterior). El Animation Pack es un paquete con un montón de animaciones con el mismo modelo que estamos usando en nuestros tutoriales.

Después de descargarlo, en la sección de Library podrás tener acceso a todo lo que descargues y desde ahí lo podrás agregar al proyecto. Agrega el Animation Pack al proyecto, verás que se te creará en el Content Browser una carpeta de nombre AnimStarterPack y dentro de ella, todo el contenido de este paquete. Tómate unos minutos y abre cada una de las animaciones para que veas todo lo que tenemos ahora para nuestros tutos :). Dentro de la carpeta AnimStarterPack además de las animaciones ya importadas tendrás la carpeta Character. Dentro de esta carpeta está el Blueprint, el AnimBlueprint el Skeletal Mesh y el resto de los recursos necesarios. Aunque de momento no usaremos el Blueprint del Character que trae por defecto el AnimStarterPack te recomiendo que le des un vistazo y lo estudies un poquito.

Creando un personaje para golpear

Voy a pasar por estos pasos bastante rápido, porque si has seguido los tutoriales no tendrás problema en hacer esto por tu cuenta.

Crea una carpeta en el Content Browser que se llame BlueEnemy. Crea un nuevo Blueprint que herede de Character y ponle de nombre BlueEnemyBlueprint. Crea un AnimationBlueprint para el esqueleto HeroTPP_Skeleton que está en /Game/AnimStarterPack y ponle BlueEnemyAnimBlueprint de nombre. Ahora abre el BlueEnemyBlueprint selecciona el Modo Default y define el Mesh de este Character con el Mesh del AnimStarterPack y el Animation Mode en Use Animation Blueprint y el BlueEnemyAnimBlueprint que acabamos de crear.

Modo Default del BlueEnemyBlueprint

Modo Default del BlueEnemyBlueprint


Pasa ahora para la sección Components y mueve el Mesh para que quede dentro de la cápsula y en la dirección correcta

Modo Components del BlueEnemyBlueprint

Modo Components del BlueEnemyBlueprint


Ahora pasa al modo Graph para abrir el Blueprint de este personaje y créale una variables nueva de nombre Health y de tipo INT y en valor por defecto ponle 100. Fíjate un detallito interesante, al crear una variable desde el blueprint puedes definirle un Tooltip. Este Tootip es un texto descriptivo para la variable que se ve cuando se pone el cursor sobre ella en el panel My Blueprint.

La variable Health será quien defina la salud de este personaje, cada vez que le demos un puñetazo perderá salud hasta que el valor de esta variable llegue a cero, cuando llega a cero muere.

Ahora abre el AnimationBlueprint para este personaje y crea una maquina de estado súper simple, solo con el estado Idle.

Maquina de estado muy simple para el BlueEnemyCharacter

Maquina de estado muy simple para el BlueEnemyCharacter


Vamos a aprovechar esta situación para poner otro ejemplo del recién aprendido AnimMontage. En realidad esto que haremos no es necesariamente con el AnimMontage, pero creo que va bien practicar un poquito lo que acabamos de aprender para que se pegue, por eso vamos a hacerlo así :) Crea un nuevo AnimMontage como lo vimos en el tutorial pasado, dale de nombre HitAnimMontage y agrégale las animaciones Hit_React_1, Hit_React_2 y Hit_React_3 que tenemos en el AnimStarterKit. Configúralo para que te quede de la siguiente forma:

HitAnimMontage que usaremos para reproducir aleatoriamente una animación de impacto en el personaje cada vez que reciba un puñetazo.

HitAnimMontage que usaremos para reproducir aleatoriamente una animación de impacto en el personaje cada vez que reciba un puñetazo.


Por último modifica el AnimGraph para agregarle este Slot entre el State Machine y el Final Animation Pose.


Ya tenemos todo lo necesario para jugar un poco con este personaje medio monigote y digo medio monigote porque básicamente lo que hará es estar en reposo, cuando reciba un puñetazo expresará su dolor reproduciendo una animación y cuando su salud llegue a cero morirá.

Para poder ver bien las colisiones entre ambos personajes podemos usar un pequeño truco. Abre el BlueEnemyBlueprint selecciona el modo Componentes, selecciona [ROOT]Capsule Component y en el panel detalles muévete hasta la sección Rendering y desmarca la propiedad Hidden In Game. Has esto mismo para el personaje protagónico. Esto nos ayudará a ver en tiempo de ejecución esta cápsula y nos ayuda a revisar en detalles las colisiones.

Pero antes de probar esto, tenemos un detallito. El componente que tiene este personaje para colisionar y bloquear a los objetos, es una cápsula. En nuestro juego solo nos desplazamos en un solo eje, pero cuando caminas hacia este otro personaje y comienzan a colisionar y a bloquearse, si intentas seguir caminando nuestro personaje patinará alrededor de la cápsula rompiendo el modo de desplazamiento de nuestro scroll-side. Pruébalo para que lo veas mejor. Para evitar esto, lo que hice fue agregar un Box Component al personaje que encierre a la cápsula y las propiedades de colisión las configuro igual a la cápsula, con el Preset: Pawn. Con esto, al ser recta la cara de la caja, se evita el problema del desplazamiento forzado.

Listo !!, agrega este personaje al escenario, recuerda que como nuestro juego es un scroll side y el personaje principal solamente se mueve hacia la derecha o la izquierda en un solo eje, para que se puedan encontrar ambos tienen que estar alineados.

Guarda, compila, ejecuta el juego y muévete en dirección al BlueEnemy. Cuando los dos componentes llegan a colisionar, ya no te puedes mover más. Si recuerdas cuando miramos la configuración de colisión para la cápsula, esta tiene marcado como Collision Response para todos los elementos: BLOCK. Por eso es que al colisionar estos dos elementos no se pueden traspasar.

Ambos personajes en el punto donde colisionan los componentes que los encierran. Como ambos están configurados como Block, aunque intentes seguir moviéndote en esa dirección no podrás avanzar más.

Ambos personajes en el punto donde colisionan los componentes que los encierran. Como ambos están configurados como Block, aunque intentes seguir moviéndote en esa dirección no podrás avanzar más.


Bien, eso está perfecto. . . ahora, lanza un puñetazo presionando la tecla R. Como notarás, no pasará absolutamente nada, y en este caso la mano traspasa el Mesh del otro personaje. Tenemos que lograr detectar la colisión del puño del personaje con el Mesh del enemigo. Para esto vamos a irnos por una solución muy simple, pero suficiente para nuestro juego. Dicho sea de paso, esta solución fue tomada del los video-tutoriales de Epic Games que te comenté en el tutorial pasado y que aprovecho para recomendártelos de nuevo :)

Vamos a agregar dos esferas que estarán ancladas a los puños del personaje. Cuando se detecte la colisión de una de esas esferas con el Mesh del otro personaje, es que estamos golpeándolo.

Agregando dos Sphere Components anclados a las manos del personaje para detectar la colisión cuando se lance un puñetazo.

Abre el Blueprint de nuestro héroe en el modo Components. Fíjate que en el panel Components encima de la jerarquía de componentes que forman parte de nuestro personaje, hay un ComboBox que dice Add Component. Desde este combobox podemos agregar nuevos componentes al personaje. Despliégalo y selecciona una Sphere, repite el proceso y agrega otra. Mueve las esferas para que queden más o menos sobre cada una de las manos del personaje, no te tiene que quedar perfecto esto es solo temporal. Cámbiale los nombres a esos componentes a PunchRightComponent y PunchLeftComponent. Puedes seleccionar las dos dando clic en una y con la tecla Ctrl presionada da clic en la otra. De esta forma podrás modificar una misma propiedad en ambos componentes al mismo tiempo. Muévete en el panel Details a la sección Rendering y desmárcale Hidden in Game. En la sección Shape, a la propiedad Sphere radius dale el valor de 15. Recuerda que el Hidden In Game es temporal, solo para poder ver el componente en el juego y poder revisar mejor las colisiones.

Blueprint del personaje principal en el modo Components con las dos esferas agregadas

Blueprint del personaje principal en el modo Components con las dos esferas agregadas


En este punto las esferas están agregadas como componente del personaje, pero tenemos que anclarlas a las manos del mismo para que se muevan junto con estas cuando se lance el puñetazo.

Hasta ahora solo hemos usado la hoja Event Graph del blueprint del personaje, pero como ya habrás notado, también contamos con una hoja en blanco de nombre Construction Script. Todo algoritmo que programemos aquí mediante visualscript se ejecutará en la construcción del objeto. Vendría jugando como el papel del constructor de nuestra clase. Modifícalo para que te quede de la siguiente forma:

Construction Script del HeroCharacterBlueprint para anclar los PunchComponents a los huesos de la mano del personaje.

Construction Script del HeroCharacterBlueprint para anclar los PunchComponents a los huesos de la mano del personaje.


Es simple lo que hacemos aquí, incluso ya lo habíamos hecho anteriormente pero desde C++. Hacemos un AttachTo de un componente a otro, como mismo hicimos con la cámara y el SpringArm en el segundo tutorial. El nodo Attach To nos permite anclar un componente a otro y le podemos especificar también el Socket al que lo anclaremos. Todo lo relacionado con los Sockets lo veremos en próximos tutoriales, de momento vasta con saber que son puntos en el objeto que podemos usarlos para anclar otro objeto. Fíjate que en el parámetro In Socket Name escribimos directamente hand_l y hand_r para cada uno de las esferas . . . uuumm, de seguro te imaginas que es esto eh ? 😉 . . . pues sí, podemos usar como socket, cualquiera de los huesos del esqueleto que usa este Mesh. Si abres el esqueleto de este personaje verás que los huesos de la mano se llaman hand_l y hand_r .

El último parámetro del nodo AttachTo es el Attach Type y nos permite definir mediante tres valores de enum como se afectará la posición y rotación de este elemento respecto al padre. En nuestro caso queremos que lo siga totalmente, así que selecciona la opción Snap to Target.

En este punto me gustaría comentarte algo. Este es el tipo de cosas que yo en lo personal prefiero hacerlas en C++, de hecho, si te fijas en nuestra clase Character toda la creación de los componentes y los Attach To los hacemos desde C++. Quise en este tutorial hacerlo mediante blueprint para ver un ejemplo de esta vía. Un muy buen ejercicio para que sigas logrando soltura con el framework de clases es que intentes hacer esto mismo pero desde C++ … y esta vez no te dejaré ninguna pista :)

Pues bien, compila, guarda y pasa al modo Components, verás que ahora salen las esferas ancladas perfectamente a las manos del personaje. Esto pasó porque al compilar se ejecuta el construction script y esta sección de componentes se actualiza. Genial verdad !?

Modo Components del Blueprint del Character con los PunchComponents anclados a la mano del personaje.

Modo Components del Blueprint del Character con los PunchComponents anclados a la mano del personaje.


Muy bien, casi terminamos aquí, solo nos queda un detalle. Para detectar la colisión entre este personaje y el enemigo vamos a usar el Evento Overlap que hablamos al inicio. O sea, podemos saber cuando dos elementos se superponen y lanzar un evento en ese preciso momento, es esa la técnica que vamos a usar para detectar cuando golpeamos al otro personaje, pero para hacer esto bien, tenemos que hacer una modificación en las propiedades de colisión de ambos PunchComponents.

Selecciona los dos, PunchRightComponent y PunchLeftComponent desde el modo Components del Blueprint del personaje y en Collision Presets selecciona OverlapAll y desmarca el check: Generate Overlap Event. Pero te preguntarás ¿Porqué desmarcar esta opción sin en realidad necesitamos que se dispare el evento cuando se detecte el overlap?. Esto es verdad, pero si desde ahora dejamos esto en true, constantemente estos componentes generarían el evento y si por ejemplo se pasa por al lado del personaje aunque sea caminando, se dispararía el evento. Como es lógico, no es esto lo que queremos, solo queremos que se detecte el evento si se está golpeando. Por lo que dinámicamente vamos a poner esta propiedad en true para cada brazo en el momento preciso y para esto vamos a usar los BranchPoints que tenemos definido en el PunchingAnimMontage.

Abre el PunchingAnimMontage y fíjate que tenemos dos BranchPoints que creamos en el tutorial pasado. Ajusta la posición de cada BranchPoint más o menos a la mitad de la animación si no lo tienes así:


Si te fijas con el timeline de la animación, cada evento se dispararía ya cuando vamos a dar el golpe y en este punto es cuando activaremos el Generate Overlap Event de la mano correspondiente y desactivamos el de la otra mano.

Abre ahora el AnimationBlueprint del personaje y modifica donde intervenimos estos eventos para que te quede de la siguiente forma:

Trozo del AnimationBlueprint de nuestro personaje donde intervenimos el evento de los BranchPoint del PunchingAnimMontage y agregamos para activar o desactivar según corresponda la propiedad Generate Overlap Event de los PunchComponents.

Trozo del AnimationBlueprint de nuestro personaje donde intervenimos el evento de los BranchPoint del PunchingAnimMontage y agregamos para activar o desactivar según corresponda la propiedad Generate Overlap Event de los PunchComponents.


Por último, para que el evento se dispare, necesitamos habilitar el Generate Overlap Event también en el otro personaje. Abre el BlueEnemyBlueprint en el Modo Components selecciona el Mesh y márcale la propiedad Generate Overlap Event ya que queremos detectar cuando uno de los dos PunchComponents del personaje colisiona con el Mesh de este otro.

BlueEnemyBlueprint en modo Components con la propiedad Generate Overlap Event para el Mesh en true.

BlueEnemyBlueprint en modo Components con la propiedad Generate Overlap Event para el Mesh en true.


Listo !! esto es todo lo que necesitamos para detectar la colisión. Vamos ahora a implementar la lógica de lo que pasa en ese momento.

Causando daño al disparar el evento Overlap entre uno de los dos PunchComponents del personaje principal y el Mesh de este otro personaje.

Vamos a intervenir el evento Overlap e implementar lo necesario para causar daño. Desde el BlueEnemyBlueprint en el modo Components selecciona el Mesh y en el panel de detalles muévete hasta la sección Events. Fíjate que esta sección tiene un combobox que dice Add Event, si lo despliegas se listan todos los eventos de este componente que podemos usar desde código.

Agregando el evento OnComponentBeginOverlap al EventGraph desde el modo Components

Agregando el evento OnComponentBeginOverlap al EventGraph desde el modo Components


Da clic en Add OnComponentBeginOverlap. Esto agregará el nodo OnComponentBeginOverlap (Mesh) al EventGraph. Ahora modifica el EventGraph para que te quede de la siguiente forma:

EventGraph del BlueEnemyBlueprint donde se aplica daño al personaje cuando se dispare el método Begin Overlap en el Mesh.

EventGraph del BlueEnemyBlueprint donde se aplica daño al personaje cuando se dispare el método Begin Overlap en el Mesh.


Aquí viene lo interesante. Cuando se dispara el método BeginOverlap en el Mesh se usa el nodo Apply Damage para aplicarle un daño a este personaje. Este nodo es súper útil, espera como parámetro cual será el actor al que se le aplicará el daño. En este caso es este mismo actor, por lo que usamos la variable self. Además, permite definirle un valor numérico de daño, en este caso le pasamos directamente 20, pero pudiéramos usar una variable para darle el valor dinámicamente. Los otros tres parámetros son opcionales y pueden resultar muy útiles. Event Instigator se usa para definir el Controller que causa el daño. Damage Causer se usa para definir el actor que causa el daño, por ejemplo, en nuestro caso pudiéramos pasar como parámetro una referencia de nuestro personaje y por último, Damage Type Class nos permite definir una clase con propiedades específicas para extender la información del daño aplicado.

Es importante en este punto aclarar que para poder usar el método Apply Damage en un Actor este tiene que tener la propiedad Can be Damaged en true. Por defecto el character la tiene en true, puedes verlo en el Modo Defaults en la sección Actor.

Por último, para probar lo que hemos hecho, agregamos un nodo Print String que nos permite imprimir el texto PUNCH ! en la pantalla.

Listo !! compila, guarda y ejecuta el juego. Acércate al otro personaje y lanza un puñetazo con la tecla R.

Captura del juego en ejecución en el preciso momento donde se lanza el evento OnComponentBeginOverlap al colisionar el PunchRightComponent con el Mesh del otro personaje.

Captura del juego en ejecución en el preciso momento donde se lanza el evento OnComponentBeginOverlap al colisionar el PunchRightComponent con el Mesh del otro personaje.


Perfecto !!, ya tenemos el momento en donde colisiona el puño con el Mesh del otro personaje y en ese punto aplicamos un daño. . . pues bien, una de las ventajas que tenemos al usar el método Apply Damage es que al aplicar un daño se lanza un evento que podemos intervenir para implementar toda la lógica cuando un personaje recibe el daño.

Vamos a intervenir este evento en el blueprint e implementar todo lo necesario para restar la salud del personaje según el daño que recibió hasta que su salud llegue a cero y muera. Pero antes de eso nos falta una cosa. Queremos que cuando el personaje reciba el golpe se reproduzca un efecto de sonido y cuando muera se reproduzca otro efecto. Vamos a usar este pretexto para tener nuestro primer acercamiento al trabajo con sonidos en Unreal Engine 4.

Introducción al trabajo con efectos de sonido en Unreal Engine 4

La música y los efectos de sonidos pueden marcar la diferencia y ser los responsables de que te quedes “como bobo“ delante de un juego. Me pasó con el Rayman Legends y hace poco con el Valiant Hearts: The Great War al escuchar su música. Por cierto, dos juegos que por nada del mundo te puedes perder :)

En Unreal Engine 4 todo lo referente al trabajo con audio se maneja dentro de unos objetos llamados Sounds Cues. Un Sound Cue se puede ver como un blueprint orientado a audio. O sea, siguiendo la misma filosofía del blueprint, del trabajo con nodos, la asociación de un nodo a otro etc, se pueden crear complejos efectos de sonido, mescla entre efectos y muchas cosas más relacionadas con el audio para nuestro juego. Al final este Sound Cue lo podemos tratar como un efecto por si solo.

Vamos a ver un simple ejemplo del trabajo con efectos de audio en UE4. Importa desde el Content Browser estos tres archivos. Son tres efectos cualesquiera para reproducir cuando el BlueEnemy reciba los golpes, puedes usar unos tuyos si los tienes a mano.

En estos momento Unreal Engine 4 solo permite importar archivos de sonido WAV de 16bits con especificaciones PCM, ADPCM, DVI ADPCM y cualquier sample rate, aunque recomiendan 44100 Hz o 22050 Hz.

Desde el Content Browser selecciona el botón Import e importa estos tres ficheros. Verás que se te muestran como Sound Wave. Puedes reproducir cada uno dando clic derecho sobre él y seleccionando la opción Play en el menú que se despliega. Desde el código se pueden reproducir estos Sound Wave directamente sin problema, pero en muchos casos queremos procesar el efecto antes de reproducirlo directamente y para esto es que usamos los Sound Cue. Vamos a ver ambos casos: Crearemos un Sound Cue para hacer que se reproduzca aleatoriamente uno de estos efectos cada vez que el personaje reciba un golpe y cuando muera reproduciremos directamente el tercero, así mismo como Sound Wave.

Para crear un Sound Cue vasta con dar clic derecho en el Content Browser y seleccionar Sounds/Sound Cue. Esto te crea un nuevo ítem de tipo Sound Cue en los recursos del proyecto y te abre directamente el Sound Cue Editor. Por defecto el Sound Cue tiene un nodo Output que representa el resultado final de todo el pre-procesamiento que se haga, como el Final Animation Pose para el caso de las animaciones. Desde aquí, solamente con nodos, podrás crear complejos efectos de sonidos, para que tengas una idea, da clic derecho en una zona en blanco y lee todas las opciones de nodos que puedes crear. Tomate un tiempo y date un recorrido general por el editor para que lo conozcas un poco. Honestamente, de este editor yo solo se lo súper básico ya que no es mi campo, pero estoy seguro que un profesional en el tema lo exprime por completo :)

Bueno, a lo nuestro, selecciona primero del Content Browser dos de los efectos, recuerda que puedes usar la tecla Ctrl para selección múltiple. Con los dos Sound Waves seleccionados abre el Sound Cue, da clic derecho en una zona en blanco y selecciona de la sección From Selected, la opción Random: Multiple WAVs y conecta la salida del nodo Random a la entrada del Output. Te quedará de la siguiente forma:

Sound Cue para reproducir aleatoriamente uno de los dos efectos de sonido.

Sound Cue para reproducir aleatoriamente uno de los dos efectos de sonido.

Con esto acabamos de crear un Sound Cue que podemos manejar como un efecto de sonido normal, pero al decirle que se reproduzca, él sólo se encargará de seleccionar aleatoriamente uno de estos dos efectos y reproducirlo. Súper verdad !! ?

Pues ya con esto estamos listo para retomar la implementación de lo que pasa cuando el personaje recibe el daño.

Interviniendo el evento Any Damage para implementar lo necesario cuando el BlueEnemy recibe el daño por un puñetazo.

Muévete a una zona en blanco del BlueEnemyBlueprint e implementa el siguiente algoritmo

Algoritmo cuando el BlueEnemy recibe daño.

Algoritmo cuando el BlueEnemy recibe daño.


Muy bien, vamos con detenimiento por todo este algoritmo porque en él usamos varios nodos que no habíamos usado antes. Primero agregamos el Nodo Event Any Damage. Este evento se dispara cuando este actor recibe daño. En este caso se dispararía cuando se detecta la colisión con el puño del personaje y se llama al Apply damage.

Fíjate que desde este evento podemos obtener el valor de daño aplicado, recuerda que en nuestro caso es 20, además podemos obtener el Damage Type, el Instigate By y el Damage Causer que como vimos, se pueden pasar como parámetros al Apply Damage.

Lo primero que hacemos es restarle la cantidad de daño aplicado a la variable Health que definimos para este personaje para representar su salud y que inicialmente está en 100. El nodo Clamp nos permite limitar el valor entre dos extremos. En este caso 0 y 100, para evitar que al finalizar la operación la variable tome valor menor que 0 o mayor que 100 en caso que fuera posible.

Después de actualizar el valor de la variable Health, usamos un Print String para ayudarnos a ver lo que pasa en cada momento. Usamos un nodo muy útil para el trabajo con strings, el nodo Append, que nos permite unir dos strings. En este caso unimos los strings “Blue Enemy Health” y el valor de la variable Health, fíjate que si intentas conectar la variable Health al puerto B del Append, como son dos variables de tipo de dato distinto, el editor automáticamente nos genera un nodo por el medio que convierte el tipo de dato int de la variable Health a string para poderlo usar con Append.

Después de eso tenemos una condición usando el nodo Branch. Preguntamos si la variable Health llegó a cero. Si es false, es que al personaje aún le queda salud y en este caso reproducimos una animación simple para reflejar el golpe. Fíjate que aquí usamos otra ventaja de los Montage. Recuerdas que en el HitAnimMontage que definimos tenemos tres secciones con tres animaciones de hit distintas que se llaman HitReact1, HitReact2 y HitReact3, verdad ? Pues aquí con el nodo Random Integer in Rage generamos un número aleatorio entre 1 y 3 creamos un string mediante el Append uniendo el string ”HitReact” con el número generado, y de esta forma obtenemos aleatoriamente el nombre de una de las secciones definidas en el AnimMontage. Por último usamos el nodo Play Anim Montage para reproducir la animación y le pasamos por el parámetro Start Section name el string generado. De esta “curiosa“ forma y con la ventaja que nos brindan los AnimMontage, cada vez que el personaje reciba un golpe tendrá una animación aleatoria para reaccionar al golpe

Por último reproducimos el Sound Cue que creamos hace unos minutos y que vimos que sería aleatoriamente uno de los dos efectos de dolor. Para esto usamos el nodo Play Sound at Location. Este nodo espera dos parámetros. El parámetro Sound que es el archivo de sonido a reproducir puede ser directamente aun Sound Wave o un Sound Cue, y el segundo parámetro nos permite definir la posición en el mundo 3D en la que se reproducirá el sonido. En este caso le pasamos la posición de este personaje.

La otra rama del Branch es cuando la variable Health llega a cero, que significa que ese último golpe mató al personaje. Pues bien, para este caso lo primero que hacemos es reproducir una animación de muerte. Pero fíjate que usamos un nuevo nodo para reproducir una animación. El nodo Play Animation nos permite reproducir un AnimSequence directamente sin tener que hacer uso del AnimationBlueprint o de los AnimMontage. El parámetro Looping tiene que estar en false, ya que queremos que esta animación se reproduzca una sola vez y quede ahí en el último frame.

También reproducimos un efecto de sonido, en este caso un Sound Wave directo, solo a modo de demostración.

Por último, hay un detalle. Si pruebas en este momento verás que todo va de maravillas pero cuando tumbas al otro personaje con el último golpe, este caerá al suelo con su animación, pero se quedarán en el medio del camino los dos componentes de colisión, la capsula y la caja. Para solucionar esto, seguido a la reproducción del efecto de sonido usamos el nodo Destroy Component que nos permite destruir un componente determinado y le pasamos el Capsule Component y el BoxComponent. Otra solución puede ser desactivarle la colisión, en vez de destruir por completo el componente.

Seguidamente, usamos el nodo Delay para demorar el algoritmo 3 segundos y por último destruimos completamente el actor de la escena. Esto provocará que después de tumbar al personaje pasaran tres segundos y su cuerpo desaparecerá del nivel.

Listo !!, compila, guarda y ejecuta el juego. Muévete hasta donde está el otro personaje y comienza a golpearlo. Verás que cada vez que le damos un puñetazo lanza una de las animaciones de impacto y cuando su salud llega a cero termina con la animación de muerte. Puedes ver con la ayuda de los Print String como disminuye la salud del otro personaje de 20 en 20 ….

Si, si, si !! . . . se que ahora mismo debes estar fijándote en que las animaciones cuando el personaje recibe un golpe están terribles, con la reacción del personaje parece más a que le están haciendo cosquillas :), pero son las animaciones que tenemos a mano :( . . . ya en nuestro juego, que el equipo de animación nos haga algo mejor :)

Captura del juego cuando el personaje le da el último puñetazo al enemigo y lo derriba.

Captura del juego cuando el personaje le da el último puñetazo al enemigo y lo derriba.



Vamos terminando aquí este tutorial, espero que te hayas divertido dándole puñetazos al BlueEnemy :). Si eres de los que prefiere el trabajo con C++ (como yo) un buen ejercicio es que intentes implementar todo lo que hemos hecho en este tutorial pero desde C++, eso te ayudará a alcanzar más soltura con el framework de clases del Engine.

En el próximo tutorial vamos a comenzar a darle armamento a nuestro personaje y ha poner más acción en nuestro juego. Puedes estar al tanto siguiéndome en Twitter (@nan2cc) . . . mientras, me encantaría escuchar tus comentarios y si tienes algún tema específico del que quisieras un tutorial también déjame un comentario, haré todo lo posible por complacerte 😉 . . . hasta la próxima, bye !!

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 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 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:

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.

#pragma once

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

class AUE4DemoGameMode : public AGameMode

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.

#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.


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:


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.
    //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.

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.


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.




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.


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:

class AHeroCharacter : public ACharacter
     * 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.


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☺.


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.