Move a Enemy to the Player

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Godot_Starter

I have a Enemy, which is an KinematicBody2D. How can I move the Enemy to other KinematicBody2D Nodes, if the name of those Nodes is Player and if they a near enough to the Enemy?

You check for player distance in enemy script

With desired distance, and move enemy state from idle to follow the player or apply shooting anything you want

Help code

var distoplay = get_global_pos(). distance_to(player.get_global_pos())

xCode Soul | 2020-02-25 11:26

:bust_in_silhouette: Reply From: njamster

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):
	if == "Player":
		target = body

func _on_Area2D_body_exited(body):
	if == "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.