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
Done. I just changed the reference of player(characterbody2D) position to getting the CollisionShape2D of player and did the same on enemy and it works so well. Before did it I was getting the reference of Character2D and it does not working because the Y coordinate was very so far each other. Now it works as I wanted
I did
func _enemy_move() -> void:
var _player_collision:Vector2 = _player_ref.get_collision_shape_2D_position()
var x_direction: float = sign(_player_collision.x - collision_shape_2d.global_position.x)
var y_direction: float = sign(_player_collision.y - collision_shape_2d.global_position.y)
_enemy_direction = Vector2(x_direction, y_direction)
velocity = _enemy_direction * speed
move_and_slide()