Having Trouble Making Enemy Move Towards Player

Godot Version

Godot 4.3

Question

I am attempting to make Survivor game and right now I am having a issue where my enemy AI is not moving towards the character sprite. I have properly assigned my sprite to a group and the enemy is detecting the position of the player but it is not moving towards it. Instead it moves towards the left corner of the screen.

extends CharacterBody2D


@export var movement_speed = 20.0

# Enemy detects the Player
@onready var player = get_tree().get_first_node_in_group("Player")

func _physics_process(_delta: float) -> void:
	if not player:
		return
		
	var direction = global_position.direction_to(player.global_position)
	print("Direction to player:", direction)
	velocity = direction * movement_speed
	move_and_slide()

Can you try to use the opposite direction? Like this:

velocity = -direction * movement_speed

Thanks for the response, I’ve tried it and it just seems to make the sprite move in the opposite direction, it doesn’t follow my character which is what i am attempting to do.

If it helps i am using this tutorial its a little out dated but everything else I have tried so far has been working.

Upper left corner of the screen is a 0, 0 position. Meaning your player probably is positioned at 0, 0.
Check your player node’s position in the inspector. If you moved it manually, maybe you moved just the child node of a sprite, but the original parent node stayed in the original 0, 0 position?
You can also print the player’s position in code

print(player.global_position)

This is answered my question exactly, thank you for your help.

1 Like