UE 動畫系統
您是 Unreal Engine 動畫系統的專家。
環境檢查
首先讀取 .agents/ue-project-context.md。注意已啟用的外掛程式(Control Rig、Motion Matching、Full Body IK)、是否使用 GAS,以及骨架/角色層級結構。
需收集的資訊
- 動畫需求為何?(移動、技能、過場動畫、IK、程序化)
- 僅 C++、僅 Blueprint、或兩者混用?
- 角色是否使用帶有現有
USkeletalMeshComponent的ACharacter? - 是否啟用 GAS?(會影響蒙太奇複製)
- 是否為多人連線?(決定複製策略)
- 專案是否使用模組化連結動畫圖層?
架構
ACharacter / AActor
└── USkeletalMeshComponent
└── UAnimInstance 子類別
├── NativeInitializeAnimation() [設定, 遊戲執行緒]
├── NativeUpdateAnimation(float dt) [遊戲執行緒]
├── NativeThreadSafeUpdateAnimation(dt) [工作者執行緒]
├── FAnimInstanceProxy [工作者執行緒評估]
└── 蒙太奇 API / 連結圖層
動畫更新分兩個階段執行。遊戲執行緒:NativeUpdateAnimation — 可安全讀取遊戲狀態。工作者執行緒:混合樹評估。所有共享狀態應在 NativeUpdateAnimation 中寫入為 UPROPERTY() Transient 成員;然後在 NativeThreadSafeUpdateAnimation 中讀取這些快取值。
AnimInstance
子類別模式
// MyAnimInstance.h
UCLASS()
class MYGAME_API UMyAnimInstance : public UAnimInstance
{
GENERATED_BODY()
virtual void NativeInitializeAnimation() override;
virtual void NativeUpdateAnimation(float DeltaSeconds) override;
virtual void NativeThreadSafeUpdateAnimation(float DeltaSeconds) override;
protected:
UPROPERTY(Transient) TObjectPtr<ACharacter> OwningCharacter;
UPROPERTY(Transient) TObjectPtr<UCharacterMovementComponent> MovementComp;
UPROPERTY(Transient, BlueprintReadOnly, Category="Locomotion")
float Speed = 0.f;
UPROPERTY(Transient, BlueprintReadOnly, Category="Locomotion")
float Direction = 0.f;
UPROPERTY(Transient, BlueprintReadOnly, Category="Locomotion")
bool bIsInAir = false;
};
// MyAnimInstance.cpp
void UMyAnimInstance::NativeInitializeAnimation()
{
Super::NativeInitializeAnimation(); // 永遠記得呼叫父類別
OwningCharacter = Cast<ACharacter>(TryGetPawnOwner());
if (OwningCharacter)
MovementComp = OwningCharacter->GetCharacterMovement();
}
void UMyAnimInstance::NativeUpdateAnimation(float DeltaSeconds)
{
Super::NativeUpdateAnimation(DeltaSeconds);
if (!OwningCharacter || !MovementComp) return;
const FVector Velocity = MovementComp->Velocity;
Speed = Velocity.Size2D();
bIsInAir = MovementComp->IsFalling();
if (Speed > 3.f)
{
const FRotator ActorRot = OwningCharacter->GetActorRotation();
const FRotator VelocityRot = Velocity.ToOrientationRotator();
Direction = UKismetMathLibrary::NormalizedDeltaRotator(
VelocityRot, ActorRot).Yaw;
}
}
void UMyAnimInstance::NativeThreadSafeUpdateAnimation(float DeltaSeconds)
{
Super::NativeThreadSafeUpdateAnimation(DeltaSeconds);
// 只能讀取上方 NativeUpdateAnimation 中寫入的 UPROPERTY 成員。
// 切勿呼叫任何未標記 BlueprintThreadSafe 的 UObject 函式。
}
FAnimInstanceProxy — 執行緒安全存取
繁重的動畫邏輯可透過 NativeThreadSafeUpdateAnimation 在工作者執行緒上執行。透過代理存取共享資料:
void UMyAnimInstance::NativeThreadSafeUpdateAnimation(float DeltaSeconds)
{
FMyAnimInstanceProxy& Proxy = GetProxyOnAnyThread<FMyAnimInstanceProxy>();
Proxy.Speed = Proxy.Velocity.Size();
Proxy.bIsFalling = Proxy.MovementMode == EMovementMode::MOVE_Falling;
}
// FAnimInstanceProxy 宣告 — 工作者執行緒資料容器
USTRUCT()
struct FMyAnimInstanceProxy : public FAnimInstanceProxy
{
GENERATED_BODY()
FMyAnimInstanceProxy() = default;
explicit FMyAnimInstanceProxy(UAnimInstance* Instance) : FAnimInstanceProxy(Instance) {}
float Speed = 0.f;
FVector Velocity = FVector::ZeroVector;
TEnumAsByte<EMovementMode> MovementMode = MOVE_None;
virtual void PreUpdate(UAnimInstance* AnimInstance, float DeltaSeconds) override;
virtual void Update(float DeltaSeconds) override;
};
// 在 UMyAnimInstance 中:覆寫 CreateAnimInstanceProxy 以回傳您的代理
virtual FAnimInstanceProxy* CreateAnimInstanceProxy() override
{ return new FMyAnimInstanceProxy(this); }
引擎會在安全的同步點於遊戲執行緒和工作者執行緒之間複製資料。
蒙太奇
來源:AnimMontage.h, AnimInstance.h
主要 API (UAnimInstance):
float Montage_Play(UAnimMontage*, float PlayRate=1.f,
EMontagePlayReturnType=MontageLength, float StartAt=0.f, bool bStopAll=true);
void Montage_Stop(float BlendOut, const UAnimMontage* Montage=nullptr);
void Montage_Pause(const UAnimMontage* Montage=nullptr);
void Montage_Resume(const UAnimMontage* Montage);
void Montage_JumpToSection(FName Section, const UAnimMontage* Montage=nullptr);
void Montage_SetNextSection(FName From, FName To, const UAnimMontage* Montage=nullptr);
bool Montage_IsActive(const UAnimMontage*) const;
bool Montage_IsPlaying(const UAnimMontage*) const;
FName Montage_GetCurrentSection(const UAnimMontage* Montage=nullptr) const;
float Montage_GetPosition(const UAnimMontage*) const;
播放 + 委派模式
void UMyComponent::PlayAttackMontage(UAnimMontage* Montage)
{
UAnimInstance* AnimInst = GetMesh()->GetAnimInstance();
if (!AnimInst || !Montage) return;
// 先播放 — Montage_SetEndDelegate 內部會呼叫 GetActiveInstanceForMontage()
// 在 Montage_Play 建立實例前,此函式會回傳 nullptr。
if (AnimInst->Montage_Play(Montage) <= 0.f) return;
FOnMontageEnded EndDelegate;
EndDelegate.BindUObject(this, &UMyComponent::OnAttackEnded);
AnimInst->Montage_SetEndDelegate(EndDelegate, Montage);
FOnMontageBlendingOutStarted BlendOutDelegate;
BlendOutDelegate.BindUObject(this, &UMyComponent::OnAttackBlendingOut);
AnimInst->Montage_SetBlendingOutDelegate(BlendOutDelegate, Montage);
}
void UMyComponent::OnAttackEnded(UAnimMontage* Montage, bool bInterrupted) { }
void UMyComponent::OnAttackBlendingOut(UAnimMontage* Montage, bool bInterrupted) { }
動態插槽蒙太奇
UAnimMontage* DynMontage = AnimInst->PlaySlotAnimationAsDynamicMontage(
SomeSequence, FName("UpperBody"), 0.25f, 0.25f, 1.f, 1);
多人連線複製
- 使用 GAS:使用
UAbilitySystemComponent::PlayMontage()— GAS 會透過FGameplayAbilityRepAnimMontage處理複製。 - 未使用 GAS:複製一個蒙太奇指標或自訂的複製結構;伺服器
呼叫
Montage_Play,客戶端在OnRep_上播放。 - 絕不應該在所有網路角色上獨立呼叫
Montage_Play而不進行同步。
GAS 整合 — PlayMontageAndWait
// GAS 技能任務 — PlayMontageAndWait(需要 GameplayAbilities 模組)
UAbilityTask_PlayMontageAndWait* Task =
UAbilityTask_PlayMontageAndWait::CreatePlayMontageAndWaitProxy(
this, NAME_None, AttackMontage, 1.f);
Task->OnCompleted.AddDynamic(this, &UMyAbility::OnMontageCompleted);
Task->OnInterrupted.AddDynamic(this, &UMyAbility::OnMontageInterrupted);
Task->ReadyForActivation(); // 必須呼叫以啟動任務
混合空間
混合空間是在 AnimGraph 中取樣的資料資產。透過設定 AnimInstance 上的 UPROPERTY 成員來驅動它們,AnimGraph 會讀取這些成員。
- 1D (
UBlendSpace1D):單一軸,通常是速度 (0–600)。 使用FInterpolationParameter,設定InterpolationType=SpringDamper,InterpolationTime=0.15,DampingRatio=1.0。 - 2D (
UBlendSpace):兩個軸 — 方向 (-180 到 180) 和速度 (0–600)。 每個速度層級都有四個主要方向的取樣。 - Aim Offset (
UAimOffsetBlendSpace):用於偏航/俯仰瞄準的加法混合空間, 放置在 AnimGraph 中基礎移動姿勢之後。
請參閱 references/locomotion-setup.md 以了解完整的軸配置和取樣放置。
狀態機
狀態機存在於 AnimGraph 中。將原生 C++ 邏輯繫結到轉換規則和狀態進入/退出,而無需 Blueprint:
// 在 NativeInitializeAnimation() 中
AddNativeTransitionBinding(
FName("LocomotionSM"), FName("Idle"), FName("Walk/Run"),
FCanTakeTransition::CreateUObject(this, &UMyAnimInstance::CanStartMoving),
FName("IdleToMoving"));
AddNativeStateEntryBinding(
FName("LocomotionSM"), FName("Land"),
FOnGraphStateChanged::CreateUObject(this, &UMyAnimInstance::OnLandEntered));
在執行時期查詢狀態機:
const FAnimNode_StateMachine* SM =
GetStateMachineInstanceFromName(FName("LocomotionSM"));
float RunWeight = GetInstanceStateWeight(
GetStateMachineIndex(FName("LocomotionSM")), SM->GetCurrentState());
轉接點
轉接點評估一個單一的布林規則,並分岔到多個目標狀態 — 取代重複的轉換邏輯。在 AnimGraph 編輯器中新增一個轉接點;其 CanEnterTransition 會執行一次,所有輸出的轉換都共享結果。當三個或更多狀態需要相同的進入條件(例如「是否在地面?」)時,請使用轉接點。對於簡單的 A 到 B 轉換,直接規則更清晰。
動畫通知
來源:AnimNotify.h, AnimNotifyState.h
UAnimNotify — 時間點
UCLASS(meta=(DisplayName="Footstep"))
class MYGAME_API UFootstepNotify : public UAnimNotify
{
GENERATED_BODY()
public:
// 永遠覆寫 UE5 的三參數簽名
virtual void Notify(USkeletalMeshComponent* MeshComp,
UAnimSequenceBase* Animation,
const FAnimNotifyEventReference& EventReference) override;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Footstep")
FName FootSocket = FName("foot_l");
};
UAnimNotifyState — 持續時間(開始/更新/結束)
UCLASS(meta=(DisplayName="Weapon Collision Window"))
class MYGAME_API UWeaponCollisionState : public UAnimNotifyState
{
GENERATED_BODY()
public:
virtual void NotifyBegin(USkeletalMeshComponent*, UAnimSequenceBase*,
float TotalDuration, const FAnimNotifyEventReference&) override;
virtual void NotifyEnd(USkeletalMeshComponent*, UAnimSequenceBase*,
const FAnimNotifyEventReference&) override;
};
分支點(同步)
在構造函數中設定 bIsNativeBranchingPoint = true。覆寫 BranchingPointNotify() 而非 Notify()。在 Montage_Advance 期間同步觸發 — 用於章節跳躍和精確的時間軸控制。所有其他通知都會被排入佇列(在更新完成後觸發,對 VFX/SFX 來說是安全的)。
命名通知委派
AnimInst->OnPlayMontageNotifyBegin.AddDynamic(
this, &UMyComponent::HandleNotifyBegin);
void UMyComponent::HandleNotifyBegin(FName NotifyName,
const FBranchingPointNotifyPayload& Payload)
{
if (NotifyName == FName("EnableHitbox")) ActivateHitDetection();
}
請參閱 references/anim-notify-reference.md 以了解內建通知目錄和更多自訂模式。
IK 與程序化動畫
使用線段追蹤的 Foot IK(NativeUpdateAnimation — 遊戲執行緒)
FVector UMyAnimInstance::GetFootTarget(FName SocketName) const
{
const FVector Foot = GetOwningComponent()->GetSocketLocation(SocketName);
FHitResult Hit;
FCollisionQueryParams P(SCENE_QUERY_STAT(FootIK), true);
P.AddIgnoredActor(OwningCharacter);
if (GetWorld()->LineTraceSingleByChannel(
Hit, Foot + FVector(0,0,50), Foot - FVector(0,0,75),
ECC_Visibility, P))
return Hit.ImpactPoint;
return Foot;
}
將結果輸入到 Control Rig 資源(推薦 UE5)或 AnimGraph 中的 Two Bone IK 骨骼控制節點。
骨骼控制節點 (AnimGraph):
| 節點 | 用途 |
|---|---|
| Two Bone IK | 雙關節 IK(手臂、腿部)— 效應器 + 關節目標 |
| FABRIK | 多段骨骼鏈 IK — 尖端骨骼 + 效應器 |
| Look At | 單一骨骼追蹤目標位置,帶有限制 |
| Copy Bone | 在骨骼之間複製變換元件 |
| Spline IK | 骨骼跟隨樣條曲線(脊椎、尾巴) |
每骨骼分層混合(上半身/下半身分離)
在 AnimGraph 中:
- 將狀態機輸出連接到基礎姿勢。
- 將
UpperBody插槽輸出連接到混合姿勢 0。 - 圖層設定:骨骼=
spine_01,深度=0,MeshPoseBlendFactor=1.0。
攻擊蒙太奇使用 UpperBody 插槽;移動動畫在下半身不受干擾地播放。
Aim Offset
// 在 NativeUpdateAnimation 中:
const FRotator Delta = UKismetMathLibrary::NormalizedDeltaRotator(
OwningCharacter->GetBaseAimRotation(),
OwningCharacter->GetActorRotation());
AimYaw = FMath::Clamp(Delta.Yaw, -90.f, 90.f);
AimPitch = FMath::Clamp(Delta.Pitch, -90.f, 90.f);
在 AnimGraph 中的基礎姿勢之後放置一個 Aim Offset 節點,並輸入 AimYaw 和 AimPitch。
連結動畫圖形與圖層
來源:AnimNode_LinkedAnimGraph.h, AnimNode_LinkedAnimLayer.h
連結動畫圖層(推薦)
- 建立一個帶有圖層函數簽名的
UAnimLayerInterfaceBlueprint。 - 主要的 AnimInstance 具有引用該介面的連結動畫圖層節點。
- 分離的 AnimInstance 子類別為每種模式實作該介面。
- 在執行時期切換:
// 切換移動實作
AnimInst->LinkAnimClassLayers(UClimbingLocomotionLayer::StaticClass());
// 將所有圖層重設為預設值:
AnimInst->LinkAnimClassLayers(nullptr);
// 檢索連結的實例:
UAnimInstance* Layer =
AnimInst->GetLinkedAnimLayerInstanceByClass(UClimbingLocomotionLayer::StaticClass());
連結動畫圖形(透過標籤)
AnimInst->LinkAnimGraphByTag(FName("CombatGraph"), UMyCombatAnimInstance::StaticClass());
UAnimInstance* Sub = AnimInst->GetLinkedAnimGraphInstanceByTag(FName("CombatGraph"));
通知傳播
AnimInst->SetReceiveNotifiesFromLinkedInstances(true);
注意:所有連結的實例都必須啟用通知 (
bReceiveNotifiesFromLinkedInstances = true),否則父級動畫實例的通知將不會傳播到子級。對於LinkedAnimLayer,請在主要 AnimInstance 上設定LinkAnimClassLayers之後,呼叫SetReceiveNotifiesFromLinkedInstances(true)。