64 lines
1.8 KiB
GDScript
64 lines
1.8 KiB
GDScript
extends Node
|
|
class_name DropManager
|
|
|
|
const PICKUP_SCENE := preload("res://pickups/pickup.tscn")
|
|
|
|
|
|
static func roll_drop(drop_table: PickupDropTable) -> Array[PickupData]:
|
|
var result: Array[PickupData] = []
|
|
if drop_table == null:
|
|
return result
|
|
|
|
if randf() > drop_table.drop_chance:
|
|
return result
|
|
|
|
var available: Array[PickupDrop] = drop_table.drops.duplicate()
|
|
available = available.filter(func(d): return d.pickup != null)
|
|
|
|
var count := randi_range(drop_table.min_drops, drop_table.max_drops)
|
|
if count < 0:
|
|
count = 0
|
|
if count > available.size():
|
|
count = available.size()
|
|
|
|
for i in range(count):
|
|
if available.is_empty():
|
|
break
|
|
var total_weight: float = 0.0
|
|
for d in available:
|
|
total_weight += max(d.weight, 0.0)
|
|
if total_weight <= 0.0:
|
|
break
|
|
var r := randf() * total_weight
|
|
var selected: PickupDrop = null
|
|
for d in available:
|
|
r -= max(d.weight, 0.0)
|
|
if r <= 0.0:
|
|
selected = d
|
|
break
|
|
if selected == null:
|
|
selected = available.back()
|
|
result.append(selected.pickup)
|
|
available.erase(selected)
|
|
|
|
return result
|
|
|
|
|
|
static func spawn_drops(drops_data: Array[PickupData], parent: Node, position: Vector2) -> void:
|
|
# Death can happen inside a physics collision callback. Adding a new Area2D
|
|
# immediately at that point is unsafe: defer its entry into the scene tree.
|
|
# Set its local position first so it never briefly enters at the origin.
|
|
var local_position: Vector2 = position
|
|
if parent is Node2D:
|
|
local_position = (parent as Node2D).to_local(position)
|
|
|
|
for data in drops_data:
|
|
if data == null:
|
|
push_warning("A drop was requested without PickupData.")
|
|
continue
|
|
var pickup := PICKUP_SCENE.instantiate() as Pickup
|
|
pickup.pickup_data = data
|
|
pickup.collection_delay_seconds = Pickup.DROP_COLLECTION_DELAY_SECONDS
|
|
pickup.position = local_position
|
|
parent.call_deferred("add_child", pickup)
|