Topic was automatically imported from the old Question2Answer platform.
Asked By
merpis
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)
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.