✨ Enemy and nest
This commit is contained in:
89
Scripts/Entities/Enemy.cs
Normal file
89
Scripts/Entities/Enemy.cs
Normal file
@@ -0,0 +1,89 @@
|
||||
using Godot;
|
||||
|
||||
namespace AceFieldNewHorizon.Scripts.Entities;
|
||||
|
||||
public partial class Enemy : CharacterBody2D
|
||||
{
|
||||
[Export] public float MoveSpeed = 150.0f;
|
||||
[Export] public float DetectionRadius = 300.0f;
|
||||
[Export] public float AttackRange = 50.0f;
|
||||
[Export] public int Damage = 10;
|
||||
[Export] public float AttackCooldown = 1.0f;
|
||||
|
||||
private Player _player;
|
||||
private float _attackTimer = 0;
|
||||
private bool _isPlayerInRange = false;
|
||||
private Area2D _detectionArea;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
// Create detection area
|
||||
_detectionArea = new Area2D();
|
||||
var collisionShape = new CollisionShape2D();
|
||||
var shape = new CircleShape2D();
|
||||
shape.Radius = DetectionRadius;
|
||||
collisionShape.Shape = shape;
|
||||
_detectionArea.AddChild(collisionShape);
|
||||
AddChild(_detectionArea);
|
||||
|
||||
// Connect signals
|
||||
_detectionArea.BodyEntered += OnBodyEnteredDetection;
|
||||
_detectionArea.BodyExited += OnBodyExitedDetection;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (_player != null && _isPlayerInRange)
|
||||
{
|
||||
// Face the player
|
||||
LookAt(_player.GlobalPosition);
|
||||
|
||||
// Move towards player if not in attack range
|
||||
var direction = GlobalPosition.DirectionTo(_player.GlobalPosition);
|
||||
var distance = GlobalPosition.DistanceTo(_player.GlobalPosition);
|
||||
|
||||
if (distance > AttackRange)
|
||||
{
|
||||
Velocity = direction * MoveSpeed;
|
||||
}
|
||||
else
|
||||
{
|
||||
Velocity = Vector2.Zero;
|
||||
TryAttackPlayer(delta);
|
||||
}
|
||||
|
||||
MoveAndSlide();
|
||||
}
|
||||
}
|
||||
|
||||
private void TryAttackPlayer(double delta)
|
||||
{
|
||||
_attackTimer += (float)delta;
|
||||
|
||||
if (_attackTimer >= AttackCooldown)
|
||||
{
|
||||
_attackTimer = 0;
|
||||
// Here you can implement the attack logic
|
||||
// For example: _player.TakeDamage(Damage);
|
||||
GD.Print("Enemy attacks player!");
|
||||
}
|
||||
}
|
||||
|
||||
private void OnBodyEnteredDetection(Node2D body)
|
||||
{
|
||||
if (body is Player player)
|
||||
{
|
||||
_player = player;
|
||||
_isPlayerInRange = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnBodyExitedDetection(Node2D body)
|
||||
{
|
||||
if (body == _player)
|
||||
{
|
||||
_isPlayerInRange = false;
|
||||
Velocity = Vector2.Zero;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user