added behavior trees!
This commit is contained in:
parent
4d0ad13bf3
commit
d362d93b12
9 changed files with 510 additions and 197 deletions
|
|
@ -9,15 +9,17 @@
|
||||||
<PublishAot>true</PublishAot>
|
<PublishAot>true</PublishAot>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Chickensoft.AutoInject" Version="2.13.11" PrivateAssets="all" />
|
<PackageReference Include="Chickensoft.AutoInject" Version="2.13.19" PrivateAssets="all" />
|
||||||
<PackageReference Include="Chickensoft.AutoInject.Analyzers" Version="2.13.11" PrivateAssets="all" OutputItemType="analyzer" />
|
<PackageReference Include="Chickensoft.AutoInject.Analyzers" Version="2.13.19" PrivateAssets="all" OutputItemType="analyzer" />
|
||||||
<PackageReference Include="Chickensoft.GodotNodeInterfaces" Version="3.0.17" />
|
<PackageReference Include="Chickensoft.Collections" Version="3.1.4" />
|
||||||
|
<PackageReference Include="Chickensoft.GodotNodeInterfaces" Version="3.0.23" />
|
||||||
<PackageReference Include="Chickensoft.Introspection" Version="3.0.3" />
|
<PackageReference Include="Chickensoft.Introspection" Version="3.0.3" />
|
||||||
<PackageReference Include="Chickensoft.Introspection.Generator" Version="3.0.3" PrivateAssets="all" OutputItemType="analyzer" />
|
<PackageReference Include="Chickensoft.Introspection.Generator" Version="3.0.3" PrivateAssets="all" OutputItemType="analyzer" />
|
||||||
<PackageReference Include="Chickensoft.LogicBlocks" Version="6.0.0" />
|
<PackageReference Include="Chickensoft.LogicBlocks" Version="6.1.1" />
|
||||||
<PackageReference Include="Chickensoft.LogicBlocks.Auto" Version="6.0.0" />
|
<PackageReference Include="Chickensoft.LogicBlocks.Auto" Version="6.1.1" />
|
||||||
<PackageReference Include="Chickensoft.LogicBlocks.DiagramGenerator" Version="6.0.0" PrivateAssets="all" OutputItemType="analyzer" />
|
<PackageReference Include="Chickensoft.LogicBlocks.DiagramGenerator" Version="6.1.1" PrivateAssets="all" OutputItemType="analyzer" />
|
||||||
<PackageReference Include="Chickensoft.LogicBlocks.Generator" Version="4.2.2" />
|
<PackageReference Include="Chickensoft.LogicBlocks.Generator" Version="4.2.2" />
|
||||||
|
<PackageReference Include="Chickensoft.Serialization" Version="3.1.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Remove="script_templates/**" />
|
<Compile Remove="script_templates/**" />
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@
|
||||||
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=player/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=player/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=script_005Ftemplates/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=script_005Ftemplates/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=script_005Ftemplates_005Cnode/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=script_005Ftemplates_005Cnode/@EntryIndexedValue">True</s:Boolean>
|
||||||
|
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=src_005Cbehavior/@EntryIndexedValue">False</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=src_005Ccombat/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=src_005Ccombat/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=src_005Ccreatures/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=src_005Ccreatures/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=src_005Ccreatures_005Cbirb/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=src_005Ccreatures_005Cbirb/@EntryIndexedValue">True</s:Boolean>
|
||||||
|
|
|
||||||
367
src/behavior/Behavior.cs
Normal file
367
src/behavior/Behavior.cs
Normal file
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Called before this node is ticked while in any state but
|
||||||
|
/// <see cref="NodeState.Running"/>.
|
||||||
|
///
|
||||||
|
/// This will be called when a node is ticked for the first time,
|
||||||
|
/// or if its last tick resulted in anything but <see cref="Result.Running"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
protected virtual void OnStart(in Context context)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Called when this Node is ticked.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context"></param>
|
||||||
|
protected abstract Result OnTick(in Context context);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Called whenever this node is halted forcibly,
|
||||||
|
/// but only if its state is <see cref="NodeState.Running"/>.
|
||||||
|
/// Therefore, this will never be called twice in a row.
|
||||||
|
/// Before being ticked again, <see cref="OnStart"/> is guaranteed
|
||||||
|
/// to be called first.
|
||||||
|
/// </summary>
|
||||||
|
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<Node>
|
||||||
|
{
|
||||||
|
public Node[] Children { get; } = children;
|
||||||
|
|
||||||
|
public IEnumerator<Node> GetEnumerator() => ((IEnumerable<Node>)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<bool> 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<bool> 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<Result> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
1
src/behavior/Behavior.cs.uid
Normal file
1
src/behavior/Behavior.cs.uid
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
uid://b13p3uohc7a3i
|
||||||
|
|
@ -20,14 +20,17 @@ public sealed partial class Hitbox : Area2D
|
||||||
|
|
||||||
private readonly Dictionary<Node2D, ImmunityEntry> _immunityEntries = [];
|
private readonly Dictionary<Node2D, ImmunityEntry> _immunityEntries = [];
|
||||||
private readonly HashSet<Node2D> _bodies = [];
|
private readonly HashSet<Node2D> _bodies = [];
|
||||||
|
private bool _checkingForHits;
|
||||||
|
|
||||||
public void OnResolved()
|
public void OnReady()
|
||||||
{
|
{
|
||||||
ProcessMode = ProcessModeEnum.Disabled;
|
|
||||||
BodyEntered += OnEntered;
|
BodyEntered += OnEntered;
|
||||||
HitboxOwner.OnHitboxAdded(this);
|
BodyExited += OnLeft;
|
||||||
|
SetPhysicsProcess(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void OnResolved() => HitboxOwner.OnHitboxAdded(this);
|
||||||
|
|
||||||
public void OnExitTree() => HitboxOwner.OnHitboxRemoved(this);
|
public void OnExitTree() => HitboxOwner.OnHitboxRemoved(this);
|
||||||
|
|
||||||
private void OnEntered(Node2D body)
|
private void OnEntered(Node2D body)
|
||||||
|
|
@ -43,7 +46,7 @@ public sealed partial class Hitbox : Area2D
|
||||||
|
|
||||||
public void OnPhysicsProcess(double delta)
|
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)
|
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());
|
if (!_immunityEntries.TryGetValue(body, out var entry)) _immunityEntries.Add(body, entry = new());
|
||||||
|
|
||||||
entry.Immunity -= (float)delta;
|
entry.Immunity -= (float)delta;
|
||||||
if (entry.Immunity <= 0f && entry.HitCount < LocalCountLimit)
|
if (_checkingForHits && entry.Immunity <= 0f && entry.HitCount < LocalCountLimit)
|
||||||
{
|
{
|
||||||
entry.Immunity += LocalImmunity;
|
entry.Immunity += LocalImmunity;
|
||||||
entry.HitCount += 1;
|
entry.HitCount += 1;
|
||||||
|
|
@ -64,7 +67,7 @@ public sealed partial class Hitbox : Area2D
|
||||||
public void StartAttack()
|
public void StartAttack()
|
||||||
{
|
{
|
||||||
if (Engine.IsEditorHint()) Visible = true;
|
if (Engine.IsEditorHint()) Visible = true;
|
||||||
ProcessMode = ProcessModeEnum.Inherit;
|
_checkingForHits = true;
|
||||||
foreach (var immunityEntry in _immunityEntries.Values)
|
foreach (var immunityEntry in _immunityEntries.Values)
|
||||||
immunityEntry.HitCount = 0;
|
immunityEntry.HitCount = 0;
|
||||||
}
|
}
|
||||||
|
|
@ -72,7 +75,7 @@ public sealed partial class Hitbox : Area2D
|
||||||
public void StopAttack()
|
public void StopAttack()
|
||||||
{
|
{
|
||||||
if (Engine.IsEditorHint()) Visible = false;
|
if (Engine.IsEditorHint()) Visible = false;
|
||||||
ProcessMode = ProcessModeEnum.Disabled;
|
_checkingForHits = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class ImmunityEntry
|
private sealed class ImmunityEntry
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,12 @@
|
||||||
using System;
|
using System;
|
||||||
using Chickensoft.LogicBlocks;
|
using System.Diagnostics;
|
||||||
using Chickensoft.LogicBlocks.Auto;
|
using Bt = Dancer.Behavior;
|
||||||
|
|
||||||
namespace Dancer;
|
namespace Dancer;
|
||||||
|
|
||||||
[Meta(typeof(IAutoNode))]
|
[Meta(typeof(IAutoNode))]
|
||||||
public sealed partial class Birb : CharacterBody2D, IAttackable, IProvide<IHitboxOwner>, IHitboxOwner
|
public sealed partial class Birb : CharacterBody2D, IAttackable,
|
||||||
|
IProvide<IHitboxOwner>, IHitboxOwner
|
||||||
{
|
{
|
||||||
public override void _Notification(int what) => this.Notify(what);
|
public override void _Notification(int what) => this.Notify(what);
|
||||||
|
|
||||||
|
|
@ -19,20 +20,83 @@ public sealed partial class Birb : CharacterBody2D, IAttackable, IProvide<IHitbo
|
||||||
[Node] private AnimatedSprite2D Body { get; set; } = null!;
|
[Node] private AnimatedSprite2D Body { get; set; } = null!;
|
||||||
[Node] private AnimationPlayer AnimationPlayer { get; set; } = null!;
|
[Node] private AnimationPlayer AnimationPlayer { get; set; } = null!;
|
||||||
|
|
||||||
|
[Node] private Hitbox StabHitbox { get; set; } = null!;
|
||||||
|
|
||||||
|
public Node2D? Target { get; set; }
|
||||||
|
|
||||||
private float _hp;
|
private float _hp;
|
||||||
|
|
||||||
private Logic Ai { get; set; } = null!;
|
private Behavior.Tree Tree { get; set; } = null!;
|
||||||
|
private float TargetVelocity { get; set; }
|
||||||
|
|
||||||
|
private MotionGoal _motionGoal = new MotionGoal.Stop();
|
||||||
|
|
||||||
|
|
||||||
|
private State _state;
|
||||||
|
|
||||||
|
private enum State
|
||||||
|
{
|
||||||
|
Idle,
|
||||||
|
Attacking,
|
||||||
|
}
|
||||||
|
|
||||||
public void Initialize()
|
public void Initialize()
|
||||||
{
|
{
|
||||||
_hp = MaxHp;
|
_hp = MaxHp;
|
||||||
HealthBar.MinValue = 0f;
|
HealthBar.MinValue = 0f;
|
||||||
HealthBar.MaxValue = MaxHp;
|
HealthBar.MaxValue = MaxHp;
|
||||||
Ai = new();
|
Tree = CreateTree();
|
||||||
Ai.Set(this);
|
|
||||||
Ai.Start<Logic.Root.Idle>();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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()
|
public void OnReady()
|
||||||
{
|
{
|
||||||
this.Provide();
|
this.Provide();
|
||||||
|
|
@ -42,13 +106,42 @@ public sealed partial class Birb : CharacterBody2D, IAttackable, IProvide<IHitbo
|
||||||
|
|
||||||
public void OnPhysicsProcess(double delta)
|
public void OnPhysicsProcess(double delta)
|
||||||
{
|
{
|
||||||
Ai.Input(new Logic.Input.OnPhysicsProcess(delta));
|
Tree.Process(delta);
|
||||||
|
|
||||||
if (!IsOnFloor()) Velocity += GetGravity() * (float)delta;
|
var velocity = Velocity;
|
||||||
|
switch (_motionGoal)
|
||||||
|
{
|
||||||
|
case MotionGoal.Stop:
|
||||||
|
if (!IsOnFloor()) break;
|
||||||
|
velocity.X = Mathf.MoveToward(Velocity.X, 0, (float)delta * Acceleration);
|
||||||
|
break;
|
||||||
|
case MotionGoal.WalkTo(var position):
|
||||||
|
if (!IsOnFloor()) break;
|
||||||
|
var xDifference = position.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.X = Mathf.MoveToward(Velocity.X, targetVelocity, (float)delta * Acceleration);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new UnreachableException();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!IsOnFloor()) velocity += GetGravity() * (float)delta;
|
||||||
|
|
||||||
|
Velocity = velocity;
|
||||||
MoveAndSlide();
|
MoveAndSlide();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private abstract record MotionGoal
|
||||||
|
{
|
||||||
|
public sealed record Stop : MotionGoal;
|
||||||
|
|
||||||
|
public sealed record WalkTo(Vector2 Position) : MotionGoal;
|
||||||
|
}
|
||||||
|
|
||||||
public void OnProcess(double delta)
|
public void OnProcess(double delta)
|
||||||
{
|
{
|
||||||
HealthBar.Value = _hp;
|
HealthBar.Value = _hp;
|
||||||
|
|
@ -58,40 +151,32 @@ public sealed partial class Birb : CharacterBody2D, IAttackable, IProvide<IHitbo
|
||||||
/// <summary>
|
/// <summary>
|
||||||
///
|
///
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="delta"></param>
|
/// <param name="position"></param>
|
||||||
/// <param name="pos"></param>
|
|
||||||
/// <returns>If the goal will be reached this tick or not.</returns>
|
/// <returns>If the goal will be reached this tick or not.</returns>
|
||||||
public bool WalkToward(double delta, Vector2 pos)
|
public bool WalkTo(Vector2 position)
|
||||||
{
|
{
|
||||||
var xDifference = pos.X - GlobalPosition.X;
|
_motionGoal = new MotionGoal.WalkTo(position);
|
||||||
var distance = Mathf.Abs(xDifference);
|
if (!IsOnFloor()) return false;
|
||||||
var breakableSpeed = Mathf.Sqrt(2 * Acceleration * distance);
|
var xDifference = position.X - GlobalPosition.X;
|
||||||
var speedRequiredToReachGoalNow = distance / (float)delta;
|
var speedRequiredToReachGoalNow = Mathf.Abs(xDifference) * Engine.PhysicsTicksPerSecond;
|
||||||
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),
|
|
||||||
};
|
|
||||||
return speedRequiredToReachGoalNow < Speed;
|
return speedRequiredToReachGoalNow < Speed;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Stop(double delta)
|
public void Stop() => _motionGoal = new MotionGoal.Stop();
|
||||||
{
|
|
||||||
Velocity = Velocity with
|
|
||||||
{
|
|
||||||
X = Mathf.MoveToward(Velocity.X, 0, (float)delta * Acceleration),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public void FaceToward(Vector2 pos)
|
public void FaceToward(Vector2 pos)
|
||||||
{
|
{
|
||||||
Body.Scale = new(pos.X > GlobalPosition.X ? 1 : -1, 1);
|
Body.Scale = new(pos.X > GlobalPosition.X ? 1 : -1, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void OnDetectionBodyEntered(Node2D body) => Ai.Input(new Logic.Input.TargetFound(body));
|
public void OnDetectionBodyEntered(Node2D body) => Target = body;
|
||||||
public void OnChaseBodyExited(Node2D body) => Ai.Input(new Logic.Input.TargetLost(body));
|
|
||||||
public void OnAttackFinished() => Ai.Input(new Logic.Input.AttackFinished());
|
public void OnChaseBodyExited(Node2D body)
|
||||||
|
{
|
||||||
|
if (Target == body) Target = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnAttackFinished() => _state = State.Idle;
|
||||||
|
|
||||||
public void GetAttacked(in Attack attack)
|
public void GetAttacked(in Attack attack)
|
||||||
{
|
{
|
||||||
|
|
@ -104,6 +189,7 @@ public sealed partial class Birb : CharacterBody2D, IAttackable, IProvide<IHitbo
|
||||||
|
|
||||||
public void OnHitboxAdded(Hitbox hitbox) => hitbox.BodyHit += OnBodyHit;
|
public void OnHitboxAdded(Hitbox hitbox) => hitbox.BodyHit += OnBodyHit;
|
||||||
public void OnHitboxRemoved(Hitbox hitbox) => hitbox.BodyHit -= OnBodyHit;
|
public void OnHitboxRemoved(Hitbox hitbox) => hitbox.BodyHit -= OnBodyHit;
|
||||||
|
|
||||||
private void OnBodyHit(Hitbox hitbox, Node2D body)
|
private void OnBodyHit(Hitbox hitbox, Node2D body)
|
||||||
{
|
{
|
||||||
if (body is not IAttackable attackable) return;
|
if (body is not IAttackable attackable) return;
|
||||||
|
|
@ -113,150 +199,4 @@ public sealed partial class Birb : CharacterBody2D, IAttackable, IProvide<IHitbo
|
||||||
Damage = 1f,
|
Damage = 1f,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
[Meta]
|
|
||||||
public sealed partial class Logic : AutoBlock
|
|
||||||
{
|
|
||||||
public sealed record Data
|
|
||||||
{
|
|
||||||
public float DurationLeft { get; set; }
|
|
||||||
public Node2D? Target { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public Logic()
|
|
||||||
{
|
|
||||||
Set(new Data());
|
|
||||||
Preallocate<Root>();
|
|
||||||
}
|
|
||||||
|
|
||||||
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<Input.TargetFound>, IGet<Input.OnPhysicsProcess>
|
|
||||||
{
|
|
||||||
public Idle()
|
|
||||||
{
|
|
||||||
this.OnEnter(() => { Get<Birb>().AnimationPlayer.Play("idle"); });
|
|
||||||
}
|
|
||||||
|
|
||||||
public Type On(in Input.TargetFound input)
|
|
||||||
{
|
|
||||||
Get<Data>().Target = input.Target;
|
|
||||||
return To<Fight.Think>();
|
|
||||||
}
|
|
||||||
|
|
||||||
public Type On(in Input.OnPhysicsProcess input)
|
|
||||||
{
|
|
||||||
Get<Birb>().Stop(input.Delta);
|
|
||||||
return ToSelf();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Meta]
|
|
||||||
public abstract partial record Fight : Root, IGet<Input.TargetLost>
|
|
||||||
{
|
|
||||||
public Type On(in Input.TargetLost input)
|
|
||||||
{
|
|
||||||
var data = Get<Data>();
|
|
||||||
if (input.Target != data.Target) return ToSelf();
|
|
||||||
data.Target = null;
|
|
||||||
return To<Idle>();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Meta]
|
|
||||||
public sealed partial record Think : Fight, IGet<Input.OnPhysicsProcess>
|
|
||||||
{
|
|
||||||
public Think()
|
|
||||||
{
|
|
||||||
this.OnEnter(() =>
|
|
||||||
{
|
|
||||||
Get<Data>().DurationLeft = (float)GD.RandRange(0f, 0.4f);
|
|
||||||
Get<Birb>().AnimationPlayer.Play("idle");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public Type On(in Input.OnPhysicsProcess input)
|
|
||||||
{
|
|
||||||
var data = Get<Data>();
|
|
||||||
var birb = Get<Birb>();
|
|
||||||
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<PrepareStrike>()
|
|
||||||
: To<StepToPosition>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Meta]
|
|
||||||
public sealed partial record StepToPosition : Fight, IGet<Input.OnPhysicsProcess>
|
|
||||||
{
|
|
||||||
public Type On(in Input.OnPhysicsProcess input)
|
|
||||||
{
|
|
||||||
var birb = Get<Birb>();
|
|
||||||
var data = Get<Data>();
|
|
||||||
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<Think>()
|
|
||||||
: ToSelf();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Meta]
|
|
||||||
public sealed partial record PrepareStrike : Fight, IGet<Input.OnPhysicsProcess>
|
|
||||||
{
|
|
||||||
public PrepareStrike()
|
|
||||||
{
|
|
||||||
this.OnEnter(() =>
|
|
||||||
{
|
|
||||||
|
|
||||||
Get<Data>().DurationLeft = (float)GD.RandRange(0.1f, 0.7f);
|
|
||||||
Get<Birb>().AnimationPlayer.Play("prepare_attack");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public Type On(in Input.OnPhysicsProcess input)
|
|
||||||
{
|
|
||||||
var data = Get<Data>();
|
|
||||||
var birb = Get<Birb>();
|
|
||||||
if (data.Target!.GlobalPosition.DistanceTo(birb.GlobalPosition) >
|
|
||||||
birb.AttackDistance * 1.2) return To<Think>();
|
|
||||||
birb.FaceToward(data.Target!.GlobalPosition);
|
|
||||||
birb.Stop(input.Delta);
|
|
||||||
data.DurationLeft -= (float)input.Delta;
|
|
||||||
return data.DurationLeft > 0f ? ToSelf() : To<Stab>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Meta]
|
|
||||||
public sealed partial record Stab : Fight, IGet<Input.AttackFinished>
|
|
||||||
{
|
|
||||||
public Stab() => this.OnEnter(() => Get<Birb>().AnimationPlayer.Play("stab"));
|
|
||||||
public Type On(in Input.AttackFinished input) => To<Think>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@
|
||||||
size = Vector2(34, 2)
|
size = Vector2(34, 2)
|
||||||
|
|
||||||
[sub_resource type="CapsuleShape2D" id="CapsuleShape2D_feb5d"]
|
[sub_resource type="CapsuleShape2D" id="CapsuleShape2D_feb5d"]
|
||||||
|
radius = 6.0
|
||||||
|
|
||||||
[sub_resource type="CircleShape2D" id="CircleShape2D_lyo8d"]
|
[sub_resource type="CircleShape2D" id="CircleShape2D_lyo8d"]
|
||||||
radius = 60.0
|
radius = 60.0
|
||||||
|
|
@ -80,6 +81,7 @@ tracks/1/keys = {
|
||||||
|
|
||||||
[sub_resource type="Animation" id="Animation_1i6dk"]
|
[sub_resource type="Animation" id="Animation_1i6dk"]
|
||||||
resource_name = "prepare_attack"
|
resource_name = "prepare_attack"
|
||||||
|
length = 24.000010357628017
|
||||||
step = 0.1
|
step = 0.1
|
||||||
tracks/0/type = "value"
|
tracks/0/type = "value"
|
||||||
tracks/0/imported = false
|
tracks/0/imported = false
|
||||||
|
|
@ -178,7 +180,6 @@ _data = {
|
||||||
collision_layer = 4
|
collision_layer = 4
|
||||||
collision_mask = 65
|
collision_mask = 65
|
||||||
script = ExtResource("1_lyo8d")
|
script = ExtResource("1_lyo8d")
|
||||||
AttackDistance = 45.0
|
|
||||||
metadata/_edit_group_ = true
|
metadata/_edit_group_ = true
|
||||||
|
|
||||||
[node name="Body" type="AnimatedSprite2D" parent="." unique_id=581143480]
|
[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]
|
[node name="StabHitbox" type="Area2D" parent="Body" unique_id=1373491990]
|
||||||
unique_name_in_owner = true
|
unique_name_in_owner = true
|
||||||
process_mode = 4
|
|
||||||
visible = false
|
visible = false
|
||||||
|
position = Vector2(20, 9)
|
||||||
collision_layer = 16
|
collision_layer = 16
|
||||||
collision_mask = 2
|
collision_mask = 2
|
||||||
script = ExtResource("3_bu42x")
|
script = ExtResource("3_bu42x")
|
||||||
|
|
||||||
[node name="CollisionShape2D" type="CollisionShape2D" parent="Body/StabHitbox" unique_id=1331922714]
|
[node name="CollisionShape2D" type="CollisionShape2D" parent="Body/StabHitbox" unique_id=1331922714]
|
||||||
position = Vector2(19, 9)
|
|
||||||
shape = SubResource("RectangleShape2D_8bh2b")
|
shape = SubResource("RectangleShape2D_8bh2b")
|
||||||
debug_color = Color(0.99607843, 0, 0.23137255, 0.41960785)
|
debug_color = Color(0.99607843, 0, 0.23137255, 0.41960785)
|
||||||
|
|
||||||
|
|
|
||||||
BIN
src/player/player.aseprite
(Stored with Git LFS)
BIN
src/player/player.aseprite
(Stored with Git LFS)
Binary file not shown.
|
|
@ -350,7 +350,6 @@ unique_name_in_owner = true
|
||||||
position = Vector2(0, -14)
|
position = Vector2(0, -14)
|
||||||
|
|
||||||
[node name="FrontKickHitBox" type="Area2D" parent="Body" unique_id=1918418417]
|
[node name="FrontKickHitBox" type="Area2D" parent="Body" unique_id=1918418417]
|
||||||
process_mode = 4
|
|
||||||
visible = false
|
visible = false
|
||||||
position = Vector2(0, -16)
|
position = Vector2(0, -16)
|
||||||
collision_layer = 8
|
collision_layer = 8
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue