extends KinematicBody2D

const SPEED: int = 35

export var creepy_hand: PackedScene

var player: KinematicBody2D = null
var velocity: Vector2 = Vector2.ZERO


func _physics_process(_delta: float) -> void:
    velocity = Vector2.ZERO

    if player:
        if position.distance_to(player.position) < 40:
            velocity = position.direction_to(player.position).normalized() * -SPEED
        elif position.distance_to(player.position) > 41:
            velocity = position.direction_to(player.position).normalized() * SPEED

    velocity = move_and_slide(velocity)
    return


func _on_player_detector_body_entered(body: Node) -> void:
    if body.is_in_group('player'):
        player = body
    return


func _on_player_detector_body_exited(body: Node) -> void:
    if body.is_in_group('player'):
        player = null
    return


func _on_projectile_timer_timeout() -> void:
    if player:
        var projectile: Node = creepy_hand.instance()
        projectile.init($Sprite.global_position, player.position)
        get_tree().get_current_scene().get_node('Projectiles').add_child(projectile)
    return
