Enemy that chases Player

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

Hey, im new to Godot and im trying to make an Enemy that chases the player.
My problem is, that the enemy just flies to the top left corner.

extends KinematicBody2D

var direction = Vector2.ZERO
onready var Spieler = get_node("/root/World/Spieler")
var Speed = 60

func _physics_process(delta):
	var to_player = ($"../Spieler".position-position).normalized()
	direction = to_player * Speed
	move_and_collide(direction * delta)

Does it work if you use the global_positions?

SteveSmith | 2022-10-20 08:16

Already tried, didnt change anything sadly

Jowawa | 2022-10-20 09:22

Fair enough. I would check the values of the positions, as it looks like it should work.

SteveSmith | 2022-10-20 10:04

:bust_in_silhouette: Reply From: KaiProton

Ive just come across this, because I wanted the enemy in my game to chase the player,

it worked fine for me in Godot 4,
all I did was change:

   onready var Spieler = get_node("/root/World/Spieler")

to

@onready var Spieler = get_node("/root/World/Spieler")

and

var to_player = ($"../Spieler".position-position).normalized()

to

var to_player = (Spieler.position-position).normalized()

and it worked fine, the to_player change was because you take the reference in the onready, then reference the node directly with $ so changed it to the variable reference.

:bust_in_silhouette: Reply From: Chad

The official docs have a great example on doing this using a NavigationRegion2D and NavigationAgent. It’s super easy and seems fast on my small world even when updating player position every physics frame. Then you can add navigation layer to your tilemap and the navigation just solves itself from then on.

I highly recommend using it sooner rather than later.