extends Node2D

const MIN_DISTANCE: int = 500

@export var spawn_points: Array[Node2D] = []
@export var spawning_object: PackedScene = null

var _distance_left: int = 0
var _spawned: bool = false


func _ready() -> void:
	RideManager.get_instance().distance_changed.connect(_on_distance_changed)
	_distance_left = randi_range(MIN_DISTANCE, Globals.get_current_track().distance - 100)


func _on_distance_changed(pixels: int) -> void:
	_distance_left -= pixels
	if _distance_left <= 0 and not _spawned:
		var spawned := spawning_object.instantiate() as Node2D
		var spawn_point: Node2D = spawn_points.pick_random()
		spawn_point.add_child.call_deferred(spawned)
		_spawned = true
