extends Node

@export var shatter_scenes: Array[PackedScene]
var shatter_scene: PackedScene

func _ready() -> void:
	var idx := randi_range(0, %Shaker.get_child_count() - 1)
	for child in %Shaker.get_children():
		child.visible = child.get_index() == idx
	shatter_scene = shatter_scenes[idx]

func _on_building_destroyed_from(global_pos: Vector3) -> void:
	var shatter = shatter_scene.instantiate()
	shatter.show()
	%Shatters.add_child(shatter)

	var meshes: Array[MeshInstance3D]

	var rbs := shatter.get_child(1).get_children()
	for rb: RigidBody3D in rbs:
		if randf() > .35: 
			rb.queue_free()
		else:
			var dir := global_pos.direction_to(rb.global_position)
			rb.apply_impulse(dir * 10)
			rb.collision_layer = 0

			meshes.push_back(rb.get_child(1))

	var t := shatter.create_tween()
	var first := true
	t.tween_interval(2.)

	for mesh in meshes:
		var t2 = t
		if not first: t2 = t.parallel()
		t2.tween_property(mesh, "transparency", 1., 0.5)
		first = false

	t.finished.connect(shatter.queue_free)
