SupaLidlGame/State/Thinker/IdleState.cs

92 lines
2.3 KiB
C#
Raw Permalink Normal View History

2023-08-05 23:50:08 -07:00
using Godot;
2023-08-08 00:54:00 -07:00
using GodotUtilities;
2023-08-05 23:50:08 -07:00
namespace SupaLidlGame.State.Thinker;
public partial class IdleState : ThinkerState
{
[Export]
public ThinkerState PursueState { get; set; }
[Export]
public float MinTargetDistance { get; set; }
2023-08-08 00:54:00 -07:00
[ExportGroup("Line of Sight")]
[Export]
public bool PursueOnLineOfSight { get; set; }
[Export]
public float MinLineOfSightDistance { get; set; }
[ExportGroup("Returning")]
[Export]
2023-12-23 22:36:09 -08:00
public bool ShouldReturnToOriginalPosition { get; set; } = true;
2023-08-08 00:54:00 -07:00
[Export]
public NavigationAgent2D NavigationAgent { get; set; }
protected Vector2 _originalPosition;
protected bool _isReturning;
public override void _Ready()
{
_originalPosition = NPC.GlobalPosition;
base._Ready();
}
2023-08-05 23:50:08 -07:00
public override ThinkerState Think()
{
var bestTarget = NPC.FindBestTarget();
2023-08-08 00:54:00 -07:00
2023-08-05 23:50:08 -07:00
if (bestTarget is not null)
{
var pos = bestTarget.GlobalPosition;
var dist = NPC.GlobalPosition.DistanceTo(pos);
if (dist < MinTargetDistance)
{
return PursueState;
}
2023-08-08 00:54:00 -07:00
else if (PursueOnLineOfSight && NPC.HasLineOfSight(bestTarget))
{
if (dist < MinLineOfSightDistance)
{
return PursueState;
}
}
_isReturning = false;
}
if (ShouldReturnToOriginalPosition)
{
if (NavigationAgent is not null)
{
// if we're less than 8 units away then we don't move
var pos = NPC.GlobalPosition;
if (!pos.IsWithinDistanceSquared(_originalPosition, 64))
{
NavigationAgent.TargetPosition = _originalPosition;
}
}
_isReturning = true;
2023-08-05 23:50:08 -07:00
}
return base.Think();
}
2023-08-08 00:54:00 -07:00
public override ThinkerState PhysicsProcess(double delta)
{
if (_isReturning && (NavigationAgent?.IsTargetReachable() ?? false))
2023-08-08 00:54:00 -07:00
{
var navPos = NavigationAgent.GetNextPathPosition();
NPC.Direction = NPC.GlobalPosition.DirectionTo(navPos);
}
if (NavigationAgent?.IsTargetReached() ?? false)
2023-08-08 00:54:00 -07:00
{
NPC.Direction = Vector2.Zero;
}
return base.PhysicsProcess(delta);
}
2023-08-05 23:50:08 -07:00
}