From 510d14fd4caadcacfa023ff73d7b2abefb14be48 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 14 Apr 2024 21:21:43 +0200 Subject: [PATCH] Create `SpawnerChoice` selecting a random subspawner to spawn things from --- behaviours/spawner_choice.gd | 34 ++++++++++++++++++++++++++++++++++ behaviours/spawner_choice.tscn | 3 +++ 2 files changed, 37 insertions(+) create mode 100644 behaviours/spawner_choice.gd create mode 100644 behaviours/spawner_choice.tscn diff --git a/behaviours/spawner_choice.gd b/behaviours/spawner_choice.gd new file mode 100644 index 0000000..71def18 --- /dev/null +++ b/behaviours/spawner_choice.gd @@ -0,0 +1,34 @@ +extends Node +class_name SpawnerChoice + + +@export var spawners: Array[Spawner] = [] +@export var weights: Array[int] = [] + + +func compute_total_weight() -> int: + var total = 0 + for weight in weights: + if weight < 0: + Log.e(self, "Weight with negative value detected.") + total += weight + return total + +func select_spawner() -> Spawner: + var total = compute_total_weight() + var sampled = Random.rng.randi_range(0, total - 1) + var idx = -1 + while sampled >= 0: + idx += 1 + sampled -= weights[idx] + return spawners[idx] + +func spawn(): + select_spawner().spawn() + + +func _ready(): + if len(spawners) != len(weights): + Log.e(self, "Spawners and weights are different lengths.") + if compute_total_weight() <= 0: + Log.e(self, "Weight total is less or equal to 0.") diff --git a/behaviours/spawner_choice.tscn b/behaviours/spawner_choice.tscn new file mode 100644 index 0000000..27deaaf --- /dev/null +++ b/behaviours/spawner_choice.tscn @@ -0,0 +1,3 @@ +[gd_scene format=3 uid="uid://cokdfsk6rgeup"] + +[node name="SpawnerChoice" type="Node"]