Attention | Topic was automatically imported from the old Question2Answer platform. | |
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
else:
velocity = Vector2(-1, 0)
if (floor($".".position.x) <= initialX):
wentToFinalPos = false
else:
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