extends ProjectileBase

var _target_enemy: Node = null

func _ready() -> void:
	super()
	speed = 400.0
	var witch = get_node("/root/Game/Witch")
	_target_enemy = witch.get_nearest_enemy(witch.global_position, _knife_filter)
	if _target_enemy == null:
		queue_free()
		return
	_target_enemy.add_to_group("knife_targeted")
	tree_exiting.connect(_on_knife_exiting)
	var dir = global_position.direction_to(_target_enemy.global_position)
	rotation = dir.angle()
	launch(_target_enemy.global_position)

func _knife_filter(enemy: Node) -> bool:
	return not enemy.is_dying and not enemy.is_hurt and not enemy.is_in_group("knife_targeted")

func _on_knife_exiting() -> void:
	if is_instance_valid(_target_enemy) and _target_enemy.is_in_group("knife_targeted"):
		_target_enemy.remove_from_group("knife_targeted")
