TExcelTAD
Home › Unreal Engine 5 with C++ › Animation Blueprints & State Machines

Animation Blueprints & State Machines

A skeletal mesh is animated by an Animation Blueprint (AnimBP): a special Blueprint whose job is to output a pose every frame. It has two graphs:

  • the Event Graph (or NativeUpdateAnimation in C++), which reads gameplay state: speed, is falling, aim pitch;
  • the AnimGraph, which turns that state into a pose: state machines, blend spaces, layered blends, IK.

The golden rule: gameplay code never plays looping animations directly. It sets variables (on the character), the AnimBP reads them and decides what to show. One-off actions (attacks, reloads) are the exception and use montages (next lesson).

The C++ AnimInstance

Give the AnimBP a C++ parent class that gathers the variables. That keeps the per-frame reading fast and the AnimBP graphs simple.

cpp
// ArenaAnimInstance.h
#pragma once

#include "CoreMinimal.h"
#include "Animation/AnimInstance.h"
#include "ArenaAnimInstance.generated.h"

class AArenaCharacter;

UCLASS()
class ARENA_API UArenaAnimInstance : public UAnimInstance
{
    GENERATED_BODY()

protected:
    virtual void NativeInitializeAnimation() override;
    virtual void NativeUpdateAnimation(float DeltaSeconds) override;

    UPROPERTY(BlueprintReadOnly, Category = "Locomotion")
    float GroundSpeed = 0.f;

    UPROPERTY(BlueprintReadOnly, Category = "Locomotion")
    bool bIsFalling = false;

    UPROPERTY(BlueprintReadOnly, Category = "Locomotion")
    bool bShouldMove = false;

    UPROPERTY(BlueprintReadOnly, Category = "Combat")
    bool bIsDead = false;

private:
    UPROPERTY()
    TObjectPtr<AArenaCharacter> Character;
};

// ArenaAnimInstance.cpp
#include "ArenaAnimInstance.h"
#include "ArenaCharacter.h"
#include "GameFramework/CharacterMovementComponent.h"

void UArenaAnimInstance::NativeInitializeAnimation()
{
    Super::NativeInitializeAnimation();
    Character = Cast<AArenaCharacter>(TryGetPawnOwner());
}

void UArenaAnimInstance::NativeUpdateAnimation(float DeltaSeconds)
{
    Super::NativeUpdateAnimation(DeltaSeconds);
    if (!Character) return;                                     // the editor preview has no pawn

    const UCharacterMovementComponent* Move = Character->GetCharacterMovement();
    GroundSpeed = Move->Velocity.Size2D();
    bIsFalling = Move->IsFalling();
    bShouldMove = GroundSpeed > 3.f && !Move->GetCurrentAcceleration().IsNearlyZero();
    bIsDead = Character->IsDead();
}

Then create the Animation Blueprint (Add → Animation → Animation Blueprint, pick the skeleton) and in Class Settings set its parent class to UArenaAnimInstance. Assign it on the character's mesh (Anim Class).

For heavy projects, NativeThreadSafeUpdateAnimation and Property Access let the update run on worker threads. Lyra's AnimBPs are built that way and are worth studying.

The AnimGraph state machine

The standard locomotion machine:

text
           bShouldMove                 bIsFalling
   [Idle] ------------> [Walk/Run] ------------> [InAir] --(!bIsFalling)--> [Land] --(time remaining < 0.1)--> back
     ^   <------------              <------------
         !bShouldMove                 !bIsFalling
   any state --(bIsDead)--> [Death]
  • States play an animation or a Blend Space (a 1D/2D grid of animations blended by parameters; BS_Locomotion blends idle → walk → run by GroundSpeed).
  • Transitions have a rule (a small graph returning bool) and a blend duration.
  • Conduits and state aliases reduce transition spaghetti ("from any of these states to Death").

A model of a state machine with blended transitions

This model evaluates transition rules each frame and cross-fades between states over the blend time, printing the weights the final pose would be blended from.

cpp · try it yourself
#include <algorithm>
#include <functional>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

struct Inputs { double Speed; bool Falling; };
struct Transition { std::string From, To; std::function<bool(const Inputs&)> Rule; double BlendTime; };

int main() {
    std::cout << std::fixed << std::setprecision(2);
    std::vector<Transition> rules = {
        {"Idle", "Run", [](const Inputs& i) { return i.Speed > 3; }, 0.2},
        {"Run", "Idle", [](const Inputs& i) { return i.Speed <= 3; }, 0.25},
        {"Run", "InAir", [](const Inputs& i) { return i.Falling; }, 0.1},
        {"Idle", "InAir", [](const Inputs& i) { return i.Falling; }, 0.1},
        {"InAir", "Idle", [](const Inputs& i) { return !i.Falling; }, 0.15},
    };

    std::string current = "Idle", previous;
    double blend = 1, blendTime = 0;                       // blend: weight of `current`, 0..1
    const double dt = 0.1;
    std::vector<Inputs> frames = {{0, false}, {300, false}, {450, false}, {450, false}, {450, true},
                                  {400, true}, {0, false}, {0, false}, {0, false}};

    for (size_t f = 0; f < frames.size(); f++) {
        for (const auto& t : rules)
            if (t.From == current && t.Rule(frames[f])) {   // first matching rule wins
                previous = current; current = t.To; blend = 0; blendTime = t.BlendTime;
                break;
            }
        if (blend < 1) blend = std::min(1.0, blend + dt / blendTime);
        std::cout << "t=" << f * dt << " speed " << std::setw(6) << frames[f].Speed << "  ";
        if (blend < 1) std::cout << current << " " << blend << " + " << previous << " " << 1 - blend << "\n";
        else std::cout << current << " 1.00\n";
    }
}
t=0.00 speed   0.00  Idle 1.00
t=0.10 speed 300.00  Run 0.50 + Idle 0.50
t=0.20 speed 450.00  Run 1.00
t=0.30 speed 450.00  Run 1.00
t=0.40 speed 450.00  InAir 1.00
t=0.50 speed 400.00  InAir 1.00
t=0.60 speed   0.00  Idle 0.67 + InAir 0.33
t=0.70 speed   0.00  Idle 1.00
t=0.80 speed   0.00  Idle 1.00

Real AnimBPs evaluate rules in a defined priority order (you can set Priority Order on transitions), and blends can use curves instead of a linear fade, but the structure is the same.

Common problems

  • Foot sliding: the animation's speed doesn't match the movement speed. Fix it in the blend space (set the axis values to the real speeds of each animation), or with Stride Warping / Distance Matching from the Animation Warping plugin.
  • Animation in the editor preview crashes the editor: TryGetPawnOwner() is null in the preview window; always null-check.
  • Twitchy transitions: a rule that flips every other frame (speed hovering near the threshold). Use two thresholds (start running above 10, stop below 3), the same hysteresis trick as in any state machine.

Test yourself

Where should the AnimBP read gameplay values such as ground speed?

  1. In the AnimGraph
  2. In the Event Graph or NativeUpdateAnimation
  3. In the GameMode
  4. In the character's constructor

Why is TryGetPawnOwner() null-checked in NativeUpdateAnimation?

  1. It is always null
  2. The AnimBP also runs in editor previews, where there is no pawn
  3. It is slow
  4. Pawns are destroyed every frame

What is a Blend Space?

  1. A level streaming volume
  2. A grid of animations blended by one or two parameters such as speed and direction
  3. A material function
  4. A physics asset