Enemy doesn't Chase player after player enters radius

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

I’m making a system where once the player enters within the radius of the Enemy, the enemy chases them and attacks them.

Upon running this code, instead of chasing them, the Enemy moves to a spot diagonal of the player and moves along with the player’s movement.

How come they aren’t actually chasing the player? I suspect that it has to do something with the velocity of the enemy, though, I’m not sure what the root cause of this is.

extends KinematicBody2D

const initialX = 150
const destinationX = 650

var velocity = Vector2()
var speed = 200
var wentToFinalPos = false
var detectedPlayer = false
var playerPosition = Vector2()
onready var player = get_parent().get_node("Player")

func _process(_delta):
	playerPosition = player.global_position
	if (detectedPlayer == false):
		if (wentToFinalPos == false):
			velocity = Vector2(1, 0)
			if (floor($".".position.x) >= destinationX):
				wentToFinalPos = true	
			velocity = Vector2(-1, 0)
			if (floor($".".position.x) <= initialX):
				wentToFinalPos = false
		velocity = (playerPosition - position)
	velocity = move_and_slide(velocity.normalized() * speed)

func _on_Detection_body_entered(body):
	if (body == player):
		detectedPlayer = true

Try using their global positions instead of their local positions? If their parent isn’t at 0,0 that might be the cause of the offset.

exuin | 2021-07-30 13:54

Even with global positions, it doesn’t work.

CattoMP4 | 2021-07-30 15:52

:bust_in_silhouette: Reply From: CattoMP4

I figured it out myself! The issue is that for some reason, the “points” (or whatever y’all call them) on the player and the enemy’s KinetaticBody2Ds aren’t the same (or similar) to make the enemy chase the player, otherwise, it ends up in a different location that is NOT the player’s location.

I made another test program while trying to figure out the issue myself is to show you how the issue is caused:

Figure 1
Figure 1: The setup that causes the issue

Figure 2
Figure 2: The setup that has the enemy go after the player, not in a random position far away from the player

Apologies for wasting anyone’s time trying to answer this question :confused: