project-dung/scripts/loot_table.gd

23 lines
544 B
GDScript

extends Reference
var item_map = {}
var total_weight = 0
func _init(items, weights):
item_map.clear()
# Calculate total weight and accumulate the weight for each item
for i in items.size():
total_weight += weights[i]
var item : Resource = items[i]
assert(item != null)
item_map[item] = total_weight
func roll_for_loot() -> Resource:
randomize()
var rng = randi() % total_weight
for item in item_map.keys():
# if the RNG is <= item cumulated weight then drop that item
if rng <= item_map[item]:
return item
return null