Navigation for enemies

This commit is contained in:
Marco 2025-01-31 15:05:45 +01:00
commit 076cff208d
7 changed files with 547 additions and 297 deletions

View file

@ -3,7 +3,7 @@ using Godot;
using System;
using System.Diagnostics;
public partial class Enemy : Area2D, IDestructible
public partial class Enemy : CharacterBody2D, IDestructible
{
private InteractionController _cachedPlayer;
private EnemyState _currentState = EnemyState.Idle;
@ -61,18 +61,47 @@ public partial class Enemy : Area2D, IDestructible
public override void _PhysicsProcess(double delta)
{
HandlePlayerDetection();
if (NavigationEnabled)
{
var moveLocation = _navigationAgent.GetNextPathPosition();
// Only do these actions if the enemy has been alerted
if (_currentState is EnemyState.Primed)
{
this.Position = moveLocation;
_navigationAgent.SetTargetPosition(_cachedPlayer.GlobalPosition);
var currentAgentPosition = GlobalPosition;
var nextPathPosition = _navigationAgent.GetNextPathPosition();
var newVelocity = currentAgentPosition.DirectionTo(nextPathPosition) * (float)(WalkSpeed * delta);
// Navigation is over, can do other things like shooting
if (_navigationAgent.IsNavigationFinished())
{
// Shoot player
HandlePlayerDetection();
return;
}
if (_navigationAgent.AvoidanceEnabled)
{
_navigationAgent.SetVelocity(newVelocity);
}
else
{
_on_navigation_agent_2d_velocity_computed(newVelocity);
}
MoveAndSlide();
}
}
}
public void _on_navigation_agent_2d_velocity_computed(Vector2 safeVelocity)
{
this.Velocity = safeVelocity;
}
@ -86,10 +115,10 @@ public partial class Enemy : Area2D, IDestructible
if (IsPlayerInSight())
{
// Update player position only if player is in sight
if (NavigationEnabled)
{
_navigationAgent.SetTargetPosition(_cachedPlayer.GlobalPosition);
}
// if (NavigationEnabled)
// {
// _navigationAgent.SetTargetPosition(_cachedPlayer.GlobalPosition);
// }
Shoot();
@ -167,7 +196,7 @@ public partial class Enemy : Area2D, IDestructible
{
}
private void Explode()
{
Debug.WriteLine("Ded");