I’m making a top-down game, I need the enemy to follow the player, but for some reason he just flies off the map, As if touching the detection_area the player pushes the enemy out, what should I do?
Script:
extends CharacterBody2D
var speed = 25
var player_chase = false
var player = null
func _physics_process(_delta):
if player_chase:
position += (player.position - position)/speed
func _on_detection_area_body_entered(_body):
player = _body
player_chase = true
func _on_detection_area_body_exited(_body):
player = null
player_chase = false
Not immediately obvious what the issue is, but I would check using global_position rather than position. If your nodes do not share a parent, funk could be occurring.
If it is just that the direction is opposite to what you want, invert it.
Previously, the player goes to the enemy and he flies to the upper left corner from the player, but now to the lower right, behind the player, It’s a pity I can’t upload a video to make it clearer
if player_chase:
var direction = (player.global_position - global_position).normalized()
velocity = direction * speed
else:
velocity = Vector2.ZERO
if global_position.distance_to(player.global_position) > 10 or global_position.distance_to(player.global_position) < -10:
move_and_slide()
if player_chase:
var direction = (player.global_position - global_position).normalized()
velocity = direction * speed
if global_position.distance_to(player.global_position) > 10 or global_position.distance_to(player.global_position) < -10:
move_and_slide()
else:
velocity = Vector2.ZERO
if player_chase:
var direction = (player.global_position - global_position).normalized()
velocity = direction * speed
if global_position.distance_to(player.global_position) > 10 or global_position.distance_to(player.global_position) < -10:
move_and_slide()
else:
velocity = Vector2.ZERO