The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

+2 votes

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?

in Engine by (378 points)

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 = getglobalpos(). distanceto(player.getglobal_pos())

1 Answer

+3 votes
Best answer

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.

by (10,634 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.