How to make enemy move toward player in Godot4 with C#

225 views Asked by At

I'm making a 2d top-down game in Godot 4 with C# and I can't get the enemy AI to move toward the player. The only time it follows the player is when the player in under the enemy and touching the enemy.

This is my code for the enemy movement:

public override void _PhysicsProcess(double delta)
{
    Move();
    MoveAndSlide();
}

public void Move()
{
    if (_player != null)
    {
        LookAt(_player.GlobalPosition);
        Vector2 direction = (GlobalPosition - _player.GlobalPosition).Normalized();
        Velocity = direction * Speed;
    }
    else
    {
        Velocity = Vector2.Zero;
    }
}
1

There are 1 answers

0
Tegai On

The current direction you are calculating should make the enemy move away from the player, try switching GlobalPosition - _player.GlobalPosition:

Vector2 direction = (_player.GlobalPosition - GlobalPosition).Normalized();