I am trying to create a function to make enemy chase the player on my game. The player moves on X and Y coordinates and the enemy needs to chase on X and Y coordinates as soon as the player change his coordinate. To do this I am trying the function below but it still does not working on Y coordinate. The X works so well but in Y coordinate enemy does not moving on player position.
How could I do it ?
var _can_attack = false
var _collision_weapon_default_positionX:float
var _raycast_default_rotate_position:float
var _player_ref:Player
var _enemy_direction:Vector2 = Vector2.ZERO
var target_position
func _physics_process(delta: float) -> void:
enemy_attack()
_flip_me()
_enemy_move()
func _enemy_move() -> void:
var x_direction = sign(_player_ref.global_position.x - global_position.x)
var y_direction = sign(_player_ref.global_position.y - global_position.y)
_enemy_direction = Vector2(x_direction, y_direction).normalized() * speed
velocity = _enemy_direction
move_and_slide()
func _flip_me() -> void:
if(_player_ref.global_position.x > global_position.x):
animated_sprite.flip_h = false
collision_shape_2d_attack.position.x = _collision_weapon_default_positionX
ray_cast_2d.rotation = _raycast_default_rotate_position
elif(_player_ref.global_position.x < global_position.x):
animated_sprite.flip_h = true
collision_shape_2d_attack.position.x = -_collision_weapon_default_positionX
ray_cast_2d.rotation = -_raycast_default_rotate_position

_enemy_directionhas, but I guess the enemy velocity could be calculated like this (if you want instant turns instead of the enemy gradually turning towards the player):velocity = (_player_ref.global_position - global_position).normalized() * speed- wherespeedis a scalar.