This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

How do you make an enemy follow the player? this code worked for me before in a separate project following a tutorial but it's not now

extends KinematicBody2D

func _physics_process(delta):
   var player = get_tree().get_root().get_node("res://Player.tscn")

   var motion = Vector2()

   position += (player.position - position)/50
   look_at(player.position)

   move_and_collide(motion)
in Engine by (16 points)

1 Answer

+1 vote

To start, I would recommend moving the player variable declaration to outside of the loop. You'll have to make this an onready variable.

It looks like the problem with your code is that you're not using the motion variable. You declare it, but you don't change it. Instead, you are changing the position directly. I would use

var motion = Vector2.ZERO
motion += position.direction_to(player.position)

and instead of using move_and_collide, use move_and_slide.

motion = move_and_slide(motion)

You can also add the look_at(player.position) line here if you want

That's it! Let me know if this works for you. I've tested this and it works in my games.

by (40 points)
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.