Attach an Area2D-node to each of your enemies. Give it a CollisionShape2D to represent the area in which the enemy is supposed to notice the player. Then attach the following script to the KinematicBody2D of your enemy:
extends KinematicBody2D
var target = null
const SPEED = 100
func _physics_process(delta):
if target:
var velocity = global_position.direction_to(target.global_position)
move_and_collide(velocity * SPEED * delta)
func _on_Area2D_body_entered(body):
print(body.name)
if body.name == "Player":
target = body
func _on_Area2D_body_exited(body):
if body.name == "Player":
target = null
Make sure you connect the body_entered
- and body_exited
-signals of the Area2D to the last two function in this script. For easier testing, also ensure that Debug > Visible Collision Shapes is active. Note that this script has a few issues when there are multiple player characters: The enemy won't follow the character closest to it, but instead the character that entered it's area last. And will stop once a character leaves the area regardless of whether there still are other players in the area. But it should give you a general idea and these issues are relatively easy to fix.