added animation playing in behavior trees

This commit is contained in:
Lilith Schier 2026-06-27 17:58:25 +02:00
parent d362d93b12
commit c9967f09d9
2 changed files with 50 additions and 11 deletions

View file

@ -11,6 +11,7 @@ public sealed class Tree(Node root)
public Node Root { get; } = root;
public EntityTable Blackboard { get; } = new();
public Random Random { get; init; } = new();
public AnimationPlayer? AnimationPlayer { get; init; }
public Result Tick() => Process(0f);
@ -21,6 +22,7 @@ public sealed class Tree(Node root)
Delta = delta,
Blackboard = Blackboard,
Random = Random,
AnimationPlayer = AnimationPlayer,
});
}
@ -95,6 +97,7 @@ public readonly record struct Context
public double Delta { get; init; }
public required EntityTable Blackboard { get; init; }
public Random Random { get; init; }
public AnimationPlayer? AnimationPlayer { get; init; }
}
public static class BehaviorTreeExtensions
@ -365,3 +368,39 @@ public sealed class Delay(double time) : Node
return Result.Running;
}
}
public sealed class PlayAnimation(StringName animation) : Node
{
public bool WaitForFinish { get; set; } = false;
private bool _hasAnimationFinished;
protected override void OnStart(in Context context)
{
if (context.AnimationPlayer is not { } animationPlayer) throw new InvalidOperationException();
animationPlayer.Play(animation);
if (WaitForFinish)
{
_hasAnimationFinished = false;
animationPlayer.AnimationFinished += OnAnimationFinished;
}
}
protected override Result OnTick(in Context context)
{
if (context.AnimationPlayer is not { } animationPlayer) throw new InvalidOperationException();
if (!WaitForFinish) return Result.Success;
if (_hasAnimationFinished)
{
animationPlayer.AnimationFinished -= OnAnimationFinished;
return Result.Success;
}
return Result.Running;
}
private void OnAnimationFinished(StringName finishedAnimation)
{
if (finishedAnimation != animation) return;
_hasAnimationFinished = true;
}
}