<style>.lazy{display:none}</style> Skip to main content
Tag

uaniminstance

Unreal Engine C++ Fundamentals – Override UAnimInstance

By Development, Tutorial, Unreal No Comments

Hey guys,

This week we continue on with fundamentals, this time going over how to override UAnimInstance in order to have more control and tighter C++ integration with our other classes.

You can find the source code for this video on the GitHub project page.

We looked at UAnimInstance before, have you gone senile !

Last time we looked at UAnimInstance was in the context of using it to access montage controls to give us finer control over our animation playback. This time we are going to move the Event Graph definition from a blue print driven anim instance and migrate all that functionality into our own C++ class.

 

Why bother rolling our own ? Blueprints are easy !

We can certainly use blueprints for all this work but having low level c++ access gives us a lot of control over our animation settings.

For example if you want to extend your animation system to support Inverse Kinematics, it becomes much simpler to compress that logic via convenient c++ method definitions rather than having to draw out a spaghetti bowl full of blue print nodes that make it hard to debug and troubleshoot.

 

Let’s take a look at some of the methods involved in this process.

virtual void NativeInitializeAnimation() override;

virtual void NativeUpdateAnimation(float DeltaTimeX) override;

NativeInitializeAnimation allows us to handle initialization of various properties on our animation instance and works similar to the InitializeComponent or BeginPlay methods on the Actor.

NativeUpdateAnimation on the other hand, works similar to the Tick functions and updates the properties for the animation blend spaces to process.

 

Interesting … I would like to subscribe to your newsletter

Now let’s take a look at the actual implementation details.

.h

UCLASS()
class UE4FUNDAMENTALS06_API UPlayerAnimInstance : public UAnimInstance
{
  GENERATED_BODY()
public:
  UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Animation")
    bool IsInAir;

  UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Animation")
    bool IsAnimationBlended;

  UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Animation")
    float Speed;

public:
  UPlayerAnimInstance();

  virtual void NativeInitializeAnimation() override;

  virtual void NativeUpdateAnimation(float DeltaTimeX) override;

private:
  APawn* Owner;
};

.cpp

void UPlayerAnimInstance::NativeInitializeAnimation()
{
  Super::NativeInitializeAnimation();

  // cache the pawn
  Owner = TryGetPawnOwner();
}

void UPlayerAnimInstance::NativeUpdateAnimation(float DeltaTimeX)
{
  Super::NativeUpdateAnimation(DeltaTimeX);

  // double check our pointers make sure nothing is empty
  if (!Owner)
  {
    return;
  }

  if (Owner->IsA(AUE4Fundamentals06Character::StaticClass()))
  {
    AUE4Fundamentals06Character* PlayerCharacter = Cast<AUE4Fundamentals06Character>(Owner);
    // again check pointers
    if (PlayerCharacter)
    {
      IsInAir = PlayerCharacter->GetMovementComponent()->IsFalling();
      IsAnimationBlended = PlayerCharacter->GetIsAnimationBlended();
      Speed = PlayerCharacter->GetVelocity().Size();

      GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, "IsInAir: " + FString(IsInAir ? "true" : "false"));
      GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, "IsAnimationBlended: " + FString(IsAnimationBlended ? "true" : "false"));
      GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, "Speed: " + FString::SanitizeFloat(Speed));
    }
  }
}

As you can see from our code, there is really not much to it.

Outside of overriding the methods you want to take control of the rest comes down how much or how little animation data you want to expose to the blueprint.

The only real major point of complication is to ensure that the pawn attached to this animation instance is correctly cast before you get at it’s details.

With your own anim instance you can now start compartmentalizing your complicated logic, handle various player types against different blend space behaviors and generally modify your animation to suit your game.

For more details check out the links below:

Unreal Engine C++ Fundamentals – UAnimInstance

By Development, Tutorial, Unreal No Comments

Hey guys,

Yet again we are going to dive into Unreal Engine C++ Fundamentals by exploring UAnimInstance aka Animation Instance.

The project for this tutorial is available on GitHub as always.

What is a Anim Instance ?

An Anim Instance is the animation instance that drives our class.

Great ! So what is an Anim Instance ?

It’s really just a container and / or facade object that interacts with our class and any animations / montages that this class is currently executing.

What it allows us to do, is have fine grain control over the state and playback of our animations.

 

That’s great for you but what about my needs ?

Well since the UAnimInstanceobject lets you take control of your animations it will be beneficial to a lot of game play mechanics.

Let’s just quickly glance over some of the parts of the Anim Instance to see how they could help by examining the PlayAnimMontage call.

float ACharacter::PlayAnimMontage(class UAnimMontage* AnimMontage, float InPlayRate, FName StartSectionName)
{
  UAnimInstance * AnimInstance = (Mesh)? Mesh->GetAnimInstance() : nullptr; 
  if( AnimMontage && AnimInstance )
  {
    float const Duration = AnimInstance->Montage_Play(AnimMontage, InPlayRate);

    if (Duration > 0.f)
    {
      // Start at a given Section.
      if( StartSectionName != NAME_None )
      {
        AnimInstance->Montage_JumpToSection(StartSectionName, AnimMontage);
      }

      return Duration;
    }
  }	

  return 0.f;
}

As you guys can see, the guys at Epic have taken a bunch of pieces of the Anim Instance class and wrapped them in a helper method.

So what is this method doing ?

  • Well it brings in the AnimInstance from our Mesh object by calling GetAnimInstance().
  • Then it validates that the montage we want to interact with is available and the Anim Instance is not null.
  • If that passes it then kicks off the Montage_Play method right on the Anim Instance by passing in the montage and the Play Rate.

So far so good.

  • We then look at a few more conditionals that just ensure the data that is required is available to us.
  • And then lastly it calls Montage_JumpToSection as the overall method takes in a StartSectionName value that determines the playback position.

 

Even Epic likes Anim Instances ? How do I subscribe to their newsletter ?

Well you can do that through their web site or simply by getting a reference to your local neighborhood Anim Instance and start performing some of these operations.

What are these common operations ?

There are a bunch of them but let’s go over the immediately meaningful ones.

Montage_Stop– stops the montage and blends in the next animation using the blend speed parameter. Good for killing montages mid playback.

// takes in a blend speed ( 1.0f ) as well as the montage
AnimInstance->Montage_Stop(1.0f, AttackMontage->Montage);

 

Montage_Pause– pauses the current animation and freezes parts of the object tied to those animations. In our case we are able to pause a punch mid stream. Great for effects where you need to halt an animation, do some other activities and then resume.

// takes in the montage you want to pause
AnimInstance->Montage_Pause(AttackMontage->Montage);

 

Montage_Resume– called after you call Montage_Pause as it will resume the playback of the animation from that point in time.

// takes in the montage you want to resume playback for
AnimInstance->Montage_Resume(AttackMontage->Montage);

 

Montage_Play – triggers the playback of an animation based on various criteria like montage, speed, return type, playback start position and a control variable to stop other montages if they are currently executing.

// kicks off the playback at a steady rate of 1 and starts playback at 0 frames
AnimInstance->Montage_Play(AttackMontage->Montage, 1.0f, EMontagePlayReturnType::Duration, 0.0f, true);

 

Montage_GetPosition– returns the current position of the playback frames as they are contained within the duration of the animation.

// returns current playback position
float CurrentPosition = AnimInstance->Montage_GetPosition(AttackMontage->Montage)

 

Montage_IsPlaying– returns a boolean to let the caller know if we have an active animation.

// checks to see if any animations in a montage are active
AnimInstance->Montage_IsPlaying

 

Montage_JumpToSectionUAnimInstance– moves the animation starting point to the location of the section as it’s setup in the Animation Montage.

// starts the animation at a specific section
AnimInstance->Montage_JumpToSection(StartSectionName, AnimMontage);

 

Pretty neat eh !

As you can see, we get a lot freedom with access to anim instances as well as the ability to control our animations easily.

Not a huge collection of additional resources but here is the doc to the UAnimInstanceclass: