diff --git a/Dancer.csproj b/Dancer.csproj
index 2df5ca7..957afd7 100644
--- a/Dancer.csproj
+++ b/Dancer.csproj
@@ -9,15 +9,17 @@
true
-
-
-
+
+
+
+
-
-
-
+
+
+
+
diff --git a/Dancer.csproj.DotSettings b/Dancer.csproj.DotSettings
index 2042eb6..4c23240 100644
--- a/Dancer.csproj.DotSettings
+++ b/Dancer.csproj.DotSettings
@@ -4,6 +4,7 @@
True
True
True
+ False
True
True
True
diff --git a/src/behavior/Behavior.cs b/src/behavior/Behavior.cs
new file mode 100644
index 0000000..09a4dee
--- /dev/null
+++ b/src/behavior/Behavior.cs
@@ -0,0 +1,367 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using Chickensoft.Collections;
+
+namespace Dancer.Behavior;
+
+public sealed class Tree(Node root)
+{
+ public Node Root { get; } = root;
+ public EntityTable Blackboard { get; } = new();
+ public Random Random { get; init; } = new();
+
+ public Result Tick() => Process(0f);
+
+ public Result Process(double delta)
+ {
+ return Root.Tick(new()
+ {
+ Delta = delta,
+ Blackboard = Blackboard,
+ Random = Random,
+ });
+ }
+
+ public void Halt() => Root.Halt();
+}
+
+public enum Result
+{
+ Running,
+ Success,
+ Failure,
+}
+
+public enum NodeState
+{
+ Idle,
+ Running,
+ Success,
+ Failure,
+}
+
+public abstract class Node
+{
+ public NodeState State { get; private set; } = NodeState.Idle;
+
+ public Result Tick(in Context context)
+ {
+ if (State is not NodeState.Running) OnStart(context);
+ var result = OnTick(in context);
+ State = result.ToState();
+ return result;
+ }
+
+ public void Halt()
+ {
+ if (State is NodeState.Running) OnHalt();
+ State = NodeState.Idle;
+ }
+
+ ///
+ /// Called before this node is ticked while in any state but
+ /// .
+ ///
+ /// This will be called when a node is ticked for the first time,
+ /// or if its last tick resulted in anything but .
+ ///
+ ///
+ protected virtual void OnStart(in Context context)
+ {
+ }
+
+ ///
+ /// Called when this Node is ticked.
+ ///
+ ///
+ protected abstract Result OnTick(in Context context);
+
+ ///
+ /// Called whenever this node is halted forcibly,
+ /// but only if its state is .
+ /// Therefore, this will never be called twice in a row.
+ /// Before being ticked again, is guaranteed
+ /// to be called first.
+ ///
+ protected virtual void OnHalt()
+ {
+ }
+}
+
+public readonly record struct Context
+{
+ public double Delta { get; init; }
+ public required EntityTable Blackboard { get; init; }
+ public Random Random { get; init; }
+}
+
+public static class BehaviorTreeExtensions
+{
+ extension(Result result)
+ {
+ public NodeState ToState() => result switch
+ {
+ Result.Running => NodeState.Running,
+ Result.Success => NodeState.Success,
+ Result.Failure => NodeState.Failure,
+ _ => throw new UnreachableException(),
+ };
+ }
+
+ extension(NodeState result)
+ {
+ public Result? ToResult() => result switch
+ {
+ NodeState.Idle => null,
+ NodeState.Running => Result.Running,
+ NodeState.Success => Result.Success,
+ NodeState.Failure => Result.Failure,
+ _ => throw new UnreachableException(),
+ };
+ }
+}
+
+public abstract class ListNode(Node[] children) : Node, IEnumerable
+{
+ public Node[] Children { get; } = children;
+
+ public IEnumerator GetEnumerator() => ((IEnumerable)Children).GetEnumerator();
+ IEnumerator IEnumerable.GetEnumerator() => Children.GetEnumerator();
+}
+
+public sealed class Sequence(Node[] children) : ListNode(children)
+{
+ private int _runningChildIdx;
+
+ protected override Result OnTick(in Context context)
+ {
+ var result = Result.Success;
+ int childIdx;
+ for (childIdx = 0; childIdx < Children.Length; childIdx++)
+ {
+ var child = Children[childIdx];
+ switch (child.Tick(context))
+ {
+ case Result.Running:
+ result = Result.Running;
+ goto LoopDone;
+ case Result.Success:
+ break;
+ case Result.Failure:
+ result = Result.Failure;
+ goto LoopDone;
+ default:
+ throw new UnreachableException();
+ }
+ }
+
+ LoopDone:
+ if (State is NodeState.Running && childIdx < _runningChildIdx)
+ {
+ Children[_runningChildIdx].Halt();
+ }
+
+ if (result is Result.Running) _runningChildIdx = childIdx;
+
+ return result;
+ }
+
+ protected override void OnHalt() => Children[_runningChildIdx].Halt();
+}
+
+public sealed class MemoSequence(Node[] children) : ListNode(children)
+{
+ private int _runningChildIdx;
+
+ protected override void OnStart(in Context context) => _runningChildIdx = 0;
+
+ protected override Result OnTick(in Context context)
+ {
+ var result = Result.Success;
+ int childIdx;
+ for (childIdx = _runningChildIdx; childIdx < Children.Length; childIdx++)
+ {
+ var child = Children[childIdx];
+ switch (child.Tick(context))
+ {
+ case Result.Running:
+ result = Result.Running;
+ goto LoopDone;
+ case Result.Success:
+ break;
+ case Result.Failure:
+ result = Result.Failure;
+ goto LoopDone;
+ default:
+ throw new UnreachableException();
+ }
+ }
+
+ LoopDone:
+ if (result is Result.Running) _runningChildIdx = childIdx;
+
+ return result;
+ }
+
+ protected override void OnHalt() => Children[_runningChildIdx].Halt();
+}
+
+public sealed class Selector(Node[] children) : ListNode(children)
+{
+ private int _runningChildIdx;
+
+ protected override Result OnTick(in Context context)
+ {
+ var result = Result.Failure;
+ int childIdx;
+ for (childIdx = 0; childIdx < Children.Length; childIdx++)
+ {
+ var child = Children[childIdx];
+ switch (child.Tick(context))
+ {
+ case Result.Running:
+ result = Result.Running;
+ goto LoopDone;
+ case Result.Success:
+ result = Result.Success;
+ goto LoopDone;
+ case Result.Failure:
+ break;
+ default:
+ throw new UnreachableException();
+ }
+ }
+
+ LoopDone:
+ if (State is NodeState.Running && childIdx < _runningChildIdx)
+ {
+ Children[_runningChildIdx].Halt();
+ }
+
+ if (result is Result.Running) _runningChildIdx = childIdx;
+
+ return result;
+ }
+
+ protected override void OnHalt() => Children[_runningChildIdx].Halt();
+}
+
+public sealed class DoNothing : Node
+{
+ protected override Result OnTick(in Context context) => Result.Running;
+}
+
+public abstract class DecoratorNode(Node child) : Node
+{
+ public Node Child { get; } = child;
+ protected override void OnHalt() => Child.Halt();
+}
+
+public sealed class Invert(Node child) : DecoratorNode(child)
+{
+ protected override Result OnTick(in Context context) =>
+ Child.Tick(context) switch
+ {
+ Result.Running => Result.Running,
+ Result.Success => Result.Failure,
+ Result.Failure => Result.Success,
+ _ => throw new UnreachableException(),
+ };
+}
+
+public sealed class AlwaysSucceed(Node child) : DecoratorNode(child)
+{
+ protected override Result OnTick(in Context context) =>
+ Child.Tick(context) switch
+ {
+ Result.Running => Result.Running,
+ Result.Success or Result.Failure => Result.Success,
+ _ => throw new UnreachableException(),
+ };
+}
+
+public sealed class AlwaysFail(Node child) : DecoratorNode(child)
+{
+ protected override Result OnTick(in Context context) =>
+ Child.Tick(context) switch
+ {
+ Result.Running => Result.Running,
+ Result.Success or Result.Failure => Result.Failure,
+ _ => throw new UnreachableException(),
+ };
+}
+
+public delegate bool OnTickCheck(in Context context);
+
+public sealed class Check(OnTickCheck predicate) : Node
+{
+ public Check(Func predicate) : this((in _) => predicate())
+ {
+ }
+
+ protected override Result OnTick(in Context context) =>
+ predicate(in context) ? Result.Success : Result.Failure;
+}
+
+public sealed class WaitUntil(OnTickCheck predicate) : Node
+{
+ public WaitUntil(Func predicate) : this((in _) => predicate())
+ {
+ }
+
+ protected override Result OnTick(in Context context) =>
+ predicate(in context) ? Result.Success : Result.Running;
+}
+
+public delegate Result OnTickAction(in Context context);
+
+public delegate void OnTickActionWithoutResult(in Context context);
+
+public sealed class Action(OnTickAction action) : Node
+{
+ public Action(System.Action action) : this((in _) =>
+ {
+ action();
+ return Result.Success;
+ })
+ {
+ }
+
+ public Action(Func action) : this((in _) => action())
+ {
+ }
+
+ public Action(OnTickActionWithoutResult action) : this((in context) =>
+ {
+ action(in context);
+ return Result.Success;
+ })
+ {
+ }
+
+ protected override Result OnTick(in Context context) => action(context);
+}
+
+public sealed class Delay(double time) : Node
+{
+ public double RandomVariation { get; set; }
+ private double TimeLeft { get; set; }
+
+ protected override void OnStart(in Context context)
+ {
+ TimeLeft = time;
+ if (RandomVariation != 0.0)
+ {
+ TimeLeft += context.Random.NextDouble() * 2.0 * RandomVariation - RandomVariation;
+ }
+ }
+
+ protected override Result OnTick(in Context context)
+ {
+ if (TimeLeft <= 0f) return Result.Success;
+ TimeLeft -= context.Delta;
+ return Result.Running;
+ }
+}
diff --git a/src/behavior/Behavior.cs.uid b/src/behavior/Behavior.cs.uid
new file mode 100644
index 0000000..8922b9e
--- /dev/null
+++ b/src/behavior/Behavior.cs.uid
@@ -0,0 +1 @@
+uid://b13p3uohc7a3i
diff --git a/src/combat/Hitbox.cs b/src/combat/Hitbox.cs
index 1846ebc..a694c35 100644
--- a/src/combat/Hitbox.cs
+++ b/src/combat/Hitbox.cs
@@ -20,14 +20,17 @@ public sealed partial class Hitbox : Area2D
private readonly Dictionary _immunityEntries = [];
private readonly HashSet _bodies = [];
+ private bool _checkingForHits;
- public void OnResolved()
+ public void OnReady()
{
- ProcessMode = ProcessModeEnum.Disabled;
BodyEntered += OnEntered;
- HitboxOwner.OnHitboxAdded(this);
+ BodyExited += OnLeft;
+ SetPhysicsProcess(true);
}
+ public void OnResolved() => HitboxOwner.OnHitboxAdded(this);
+
public void OnExitTree() => HitboxOwner.OnHitboxRemoved(this);
private void OnEntered(Node2D body)
@@ -43,7 +46,7 @@ public sealed partial class Hitbox : Area2D
public void OnPhysicsProcess(double delta)
{
- foreach (var body in _bodies) CheckForHit(body);
+ foreach (var body in _bodies) CheckForHit(body, delta);
}
private void CheckForHit(Node2D body, double delta = 0.0)
@@ -51,7 +54,7 @@ public sealed partial class Hitbox : Area2D
if (!_immunityEntries.TryGetValue(body, out var entry)) _immunityEntries.Add(body, entry = new());
entry.Immunity -= (float)delta;
- if (entry.Immunity <= 0f && entry.HitCount < LocalCountLimit)
+ if (_checkingForHits && entry.Immunity <= 0f && entry.HitCount < LocalCountLimit)
{
entry.Immunity += LocalImmunity;
entry.HitCount += 1;
@@ -64,7 +67,7 @@ public sealed partial class Hitbox : Area2D
public void StartAttack()
{
if (Engine.IsEditorHint()) Visible = true;
- ProcessMode = ProcessModeEnum.Inherit;
+ _checkingForHits = true;
foreach (var immunityEntry in _immunityEntries.Values)
immunityEntry.HitCount = 0;
}
@@ -72,7 +75,7 @@ public sealed partial class Hitbox : Area2D
public void StopAttack()
{
if (Engine.IsEditorHint()) Visible = false;
- ProcessMode = ProcessModeEnum.Disabled;
+ _checkingForHits = false;
}
private sealed class ImmunityEntry
diff --git a/src/creatures/birb/Birb.cs b/src/creatures/birb/Birb.cs
index 9c90533..039ded8 100644
--- a/src/creatures/birb/Birb.cs
+++ b/src/creatures/birb/Birb.cs
@@ -1,11 +1,12 @@
using System;
-using Chickensoft.LogicBlocks;
-using Chickensoft.LogicBlocks.Auto;
+using System.Diagnostics;
+using Bt = Dancer.Behavior;
namespace Dancer;
[Meta(typeof(IAutoNode))]
-public sealed partial class Birb : CharacterBody2D, IAttackable, IProvide, IHitboxOwner
+public sealed partial class Birb : CharacterBody2D, IAttackable,
+ IProvide, IHitboxOwner
{
public override void _Notification(int what) => this.Notify(what);
@@ -19,20 +20,83 @@ public sealed partial class Birb : CharacterBody2D, IAttackable, IProvide();
+ Tree = CreateTree();
}
+ private Bt.Tree CreateTree() => new(
+ new Bt.Selector([
+ new Bt.Sequence([
+ new Bt.Check(() => Target is not null),
+ new Bt.Action(() => FaceToward(Target!.GlobalPosition)),
+ new Bt.Selector([
+ new Bt.MemoSequence([
+ new Bt.Sequence([
+ new Bt.Check(() => StabHitbox.GetOverlappingBodies().Contains(Target)),
+ new Bt.MemoSequence([
+ new Bt.Action(Stop),
+ new Bt.Action(() => AnimationPlayer.Play("prepare_attack")),
+ new Bt.Delay(0.4) { RandomVariation = 0.2 },
+ ]),
+ ]),
+ new Bt.Action(() =>
+ {
+ AnimationPlayer.Play("stab");
+ _state = State.Attacking;
+ }),
+ new Bt.WaitUntil(() => _state is State.Idle),
+ ]),
+ new Bt.MemoSequence([
+ new Bt.Delay(0.1) { RandomVariation = 0.05 },
+ new Bt.Action(() =>
+ {
+ var left = Target!.GlobalPosition + Vector2.Left * AttackDistance;
+ var right = Target!.GlobalPosition + Vector2.Right * AttackDistance;
+ var targetPosition =
+ GlobalPosition.DistanceSquaredTo(left)
+ < GlobalPosition.DistanceSquaredTo(right)
+ ? left
+ : right;
+ AnimationPlayer.Play("idle");
+ return WalkTo(targetPosition)
+ ? Bt.Result.Success
+ : Bt.Result.Running;
+ }),
+ ]),
+ ]),
+ ]),
+ new Bt.MemoSequence([
+ new Bt.Check(() => _state is State.Idle),
+ new Bt.Action(() => AnimationPlayer.Play("idle")),
+ new Bt.DoNothing(),
+ ]),
+ ])
+ );
+
public void OnReady()
{
this.Provide();
@@ -42,13 +106,42 @@ public sealed partial class Birb : CharacterBody2D, IAttackable, IProvide
///
///
- ///
- ///
+ ///
/// If the goal will be reached this tick or not.
- public bool WalkToward(double delta, Vector2 pos)
+ public bool WalkTo(Vector2 position)
{
- var xDifference = pos.X - GlobalPosition.X;
- var distance = Mathf.Abs(xDifference);
- var breakableSpeed = Mathf.Sqrt(2 * Acceleration * distance);
- var speedRequiredToReachGoalNow = distance / (float)delta;
- var speed = Mathf.Min(Speed, Mathf.Min(speedRequiredToReachGoalNow, breakableSpeed));
- var targetVelocity = Mathf.Sign(xDifference) * speed;
- Velocity = Velocity with
- {
- X = Mathf.MoveToward(Velocity.X, targetVelocity, (float)delta * Acceleration),
- };
+ _motionGoal = new MotionGoal.WalkTo(position);
+ if (!IsOnFloor()) return false;
+ var xDifference = position.X - GlobalPosition.X;
+ var speedRequiredToReachGoalNow = Mathf.Abs(xDifference) * Engine.PhysicsTicksPerSecond;
return speedRequiredToReachGoalNow < Speed;
}
- public void Stop(double delta)
- {
- Velocity = Velocity with
- {
- X = Mathf.MoveToward(Velocity.X, 0, (float)delta * Acceleration),
- };
- }
+ public void Stop() => _motionGoal = new MotionGoal.Stop();
public void FaceToward(Vector2 pos)
{
Body.Scale = new(pos.X > GlobalPosition.X ? 1 : -1, 1);
}
- public void OnDetectionBodyEntered(Node2D body) => Ai.Input(new Logic.Input.TargetFound(body));
- public void OnChaseBodyExited(Node2D body) => Ai.Input(new Logic.Input.TargetLost(body));
- public void OnAttackFinished() => Ai.Input(new Logic.Input.AttackFinished());
+ public void OnDetectionBodyEntered(Node2D body) => Target = body;
+
+ public void OnChaseBodyExited(Node2D body)
+ {
+ if (Target == body) Target = null;
+ }
+
+ public void OnAttackFinished() => _state = State.Idle;
public void GetAttacked(in Attack attack)
{
@@ -104,6 +189,7 @@ public sealed partial class Birb : CharacterBody2D, IAttackable, IProvide hitbox.BodyHit += OnBodyHit;
public void OnHitboxRemoved(Hitbox hitbox) => hitbox.BodyHit -= OnBodyHit;
+
private void OnBodyHit(Hitbox hitbox, Node2D body)
{
if (body is not IAttackable attackable) return;
@@ -113,150 +199,4 @@ public sealed partial class Birb : CharacterBody2D, IAttackable, IProvide();
- }
-
- public static class Input
- {
- public readonly record struct AttackFinished;
-
- public readonly record struct TargetFound(Node2D Target);
-
- public readonly record struct TargetLost(Node2D Target);
-
- public readonly record struct OnPhysicsProcess(double Delta);
- }
-
- [Meta, StateDiagram]
- public abstract partial record Root : LogicBlockState
- {
- [Meta]
- public sealed partial record Idle : Root, IGet, IGet
- {
- public Idle()
- {
- this.OnEnter(() => { Get().AnimationPlayer.Play("idle"); });
- }
-
- public Type On(in Input.TargetFound input)
- {
- Get().Target = input.Target;
- return To();
- }
-
- public Type On(in Input.OnPhysicsProcess input)
- {
- Get().Stop(input.Delta);
- return ToSelf();
- }
- }
-
- [Meta]
- public abstract partial record Fight : Root, IGet
- {
- public Type On(in Input.TargetLost input)
- {
- var data = Get();
- if (input.Target != data.Target) return ToSelf();
- data.Target = null;
- return To();
- }
-
- [Meta]
- public sealed partial record Think : Fight, IGet
- {
- public Think()
- {
- this.OnEnter(() =>
- {
- Get().DurationLeft = (float)GD.RandRange(0f, 0.4f);
- Get().AnimationPlayer.Play("idle");
- });
- }
-
- public Type On(in Input.OnPhysicsProcess input)
- {
- var data = Get();
- var birb = Get();
- data.DurationLeft -= (float)input.Delta;
- if (data.DurationLeft > 0f) return ToSelf();
-
- birb.FaceToward(data.Target!.GlobalPosition);
- birb.Stop(input.Delta);
- return data.Target!.GlobalPosition.DistanceTo(birb.GlobalPosition) < birb.AttackDistance
- ? To()
- : To();
- }
- }
-
- [Meta]
- public sealed partial record StepToPosition : Fight, IGet
- {
- public Type On(in Input.OnPhysicsProcess input)
- {
- var birb = Get();
- var data = Get();
- birb.FaceToward(data.Target!.GlobalPosition);
-
- var left = data.Target!.GlobalPosition + Vector2.Left * birb.AttackDistance;
- var right = data.Target!.GlobalPosition + Vector2.Right * birb.AttackDistance;
- var targetPosition =
- birb.GlobalPosition.DistanceSquaredTo(left)
- < birb.GlobalPosition.DistanceSquaredTo(right)
- ? left
- : right;
- return birb.WalkToward(input.Delta, targetPosition)
- ? To()
- : ToSelf();
- }
- }
-
- [Meta]
- public sealed partial record PrepareStrike : Fight, IGet
- {
- public PrepareStrike()
- {
- this.OnEnter(() =>
- {
-
- Get().DurationLeft = (float)GD.RandRange(0.1f, 0.7f);
- Get().AnimationPlayer.Play("prepare_attack");
- });
- }
-
- public Type On(in Input.OnPhysicsProcess input)
- {
- var data = Get();
- var birb = Get();
- if (data.Target!.GlobalPosition.DistanceTo(birb.GlobalPosition) >
- birb.AttackDistance * 1.2) return To();
- birb.FaceToward(data.Target!.GlobalPosition);
- birb.Stop(input.Delta);
- data.DurationLeft -= (float)input.Delta;
- return data.DurationLeft > 0f ? ToSelf() : To();
- }
- }
-
- [Meta]
- public sealed partial record Stab : Fight, IGet
- {
- public Stab() => this.OnEnter(() => Get().AnimationPlayer.Play("stab"));
- public Type On(in Input.AttackFinished input) => To();
- }
- }
- }
- }
}
diff --git a/src/creatures/birb/birb.tscn b/src/creatures/birb/birb.tscn
index f84d88f..cf49050 100644
--- a/src/creatures/birb/birb.tscn
+++ b/src/creatures/birb/birb.tscn
@@ -8,6 +8,7 @@
size = Vector2(34, 2)
[sub_resource type="CapsuleShape2D" id="CapsuleShape2D_feb5d"]
+radius = 6.0
[sub_resource type="CircleShape2D" id="CircleShape2D_lyo8d"]
radius = 60.0
@@ -80,6 +81,7 @@ tracks/1/keys = {
[sub_resource type="Animation" id="Animation_1i6dk"]
resource_name = "prepare_attack"
+length = 24.000010357628017
step = 0.1
tracks/0/type = "value"
tracks/0/imported = false
@@ -178,7 +180,6 @@ _data = {
collision_layer = 4
collision_mask = 65
script = ExtResource("1_lyo8d")
-AttackDistance = 45.0
metadata/_edit_group_ = true
[node name="Body" type="AnimatedSprite2D" parent="." unique_id=581143480]
@@ -190,14 +191,13 @@ offset = Vector2(9, -4)
[node name="StabHitbox" type="Area2D" parent="Body" unique_id=1373491990]
unique_name_in_owner = true
-process_mode = 4
visible = false
+position = Vector2(20, 9)
collision_layer = 16
collision_mask = 2
script = ExtResource("3_bu42x")
[node name="CollisionShape2D" type="CollisionShape2D" parent="Body/StabHitbox" unique_id=1331922714]
-position = Vector2(19, 9)
shape = SubResource("RectangleShape2D_8bh2b")
debug_color = Color(0.99607843, 0, 0.23137255, 0.41960785)
diff --git a/src/player/player.aseprite b/src/player/player.aseprite
index bf6be7a..2190ce3 100644
--- a/src/player/player.aseprite
+++ b/src/player/player.aseprite
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:5e902f83438b0e5694851b0129120802806f61041f118ac4de8dc81a0d836adf
-size 6856
+oid sha256:0b4252b5d9c0af105bc74fa2827ff9488115eca4e76bc49143718c17bf81d700
+size 6855
diff --git a/src/player/player.tscn b/src/player/player.tscn
index 2952ab1..095830f 100644
--- a/src/player/player.tscn
+++ b/src/player/player.tscn
@@ -350,7 +350,6 @@ unique_name_in_owner = true
position = Vector2(0, -14)
[node name="FrontKickHitBox" type="Area2D" parent="Body" unique_id=1918418417]
-process_mode = 4
visible = false
position = Vector2(0, -16)
collision_layer = 8