How can I play animations strictly from C++?

Partial answers:

Playing Blend Spaces from C++:

  • Set a UPROPERTY for your BlendSpace to be set in the Editor:

     UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "Anims")
     UBlendSpace1D *BlendSpace;
    
  • Play the animation and set the BlendSpace parameter (0-100 how far to mix the anims). In this example, I have a 1D BlendSpace that I’m blending along the ‘X’ axis (as set in the editor):

    ASkeletalMeshActor *Skel = Cast<ASkeletalMeshActor>(MyActor);
     if (Skel)
     {
         USkeletalMeshComponent *Mesh = Skel->GetSkeletalMeshComponent();
         if (Mesh)
         {
             Mesh->PlayAnimation(BlendSpace, true);
             FVector BlendParams(50.0f, 0.0f, 0.0f);
             Mesh->GetSingleNodeInstance()->SetBlendSpaceInput(BlendParams);
         }
    

    }

The example used is with a 1D Blend Space, but it also work for 2D or 3D blend spaces :slight_smile:

To Play an animation in a slot:

  • As before add the UPROPERTY with the animation sequence to play:

    UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = “Anims”)
    UAnimSequence *MyAnimSequence;

  • Play the Animation:

     USkeletalMeshComponent *Mesh = MyActor->FindComponentByClass<USkeletalMeshComponent>();
     if (Mesh)
     {
         UAnimInstance *AnimInst = Mesh->GetAnimInstance();
         if (AnimInst)
         {
             AnimInst->PlaySlotAnimationAsDynamicMontage(MyAnimSequence, TEXT("UpperBody"), 0.1f, 0.1f, 1.0f, 30.0f);
         }
     }
    

To Play a simple full body animation and stop at the end:

MyAnimTimer = AnimInstance->Montage_Play(MyMontage);
GetWorldTimerManager().SetTimer(PauseMontageTimerHandle, this, &MyActor::PauseMontageFunc, MyAnimTimer, false);

Where MyAnimTimer is a float, and PauseMontageTimerHandle is a FTimerHandle.

In MyActor::PauseMontageFunc:

AnimInst->Montage_Pause();

To Play a simple full body animation and jump ahead to a section. Montage_Play(anim, play speed) and Montage_JumpToSection.

To Play an animation additively use the PlaySlotAnimationAsDynamicMontage function as before, into a slot set up like this: Using Layered Animations in Unreal Engine | Unreal Engine 5.1 Documentation

2 Likes