Each if randf() < weight in a chain only runs when the ones before it failed, so later entries get a fraction of their chance and sometimes nothing drops at all. In our Godot 4.7 test a 50/30/15/5 table came out 50.0/15.1/5.3/1.4, with nothing 28.1% of the time. Roll once with rng.rand_weighted(weights), available since Godot 4.3.
The code
Make the table a Dictionary of entry and weight, and call pick(table). The weights do not need to add up to 100. It returns null when every weight is 0. Set rng.seed if you need the same rolls every time, for example for a daily reward.
extends Node
## Pick one entry from a weighted table: herb drops, chest rewards, pill quality.
## Weights do not need to add up to 100. Needs Godot 4.3 or newer for rand_weighted().
var rng := RandomNumberGenerator.new()
func pick(table: Dictionary) -> Variant:
var keys := table.keys()
var weights := PackedFloat32Array()
for k in keys:
weights.append(float(table[k]))
var i := rng.rand_weighted(weights) # -1 when every weight is 0
return keys[i] if i >= 0 else null
What we measured
100,000 rolls of a table with Common Herb 50, Spirit Grass 30, Moon Lotus 15 and Dragon Blood Vine 5, with a fixed seed. Two runs with the same numbers.
- A chain of if randf() checks, most common first: 50.0%, 15.1%, 5.3% and 1.4%, and nothing 28.1% of the time. The rarest herb dropped less than a third as often as its weight says.
- The same chain, rarest first: 28.3%, 24.2%, 14.4% and 5.0%, nothing 28.1%. Same weights, different order, different game.
rand_weighted(): 50.0%, 30.0%, 15.1% and 4.9%, never nothing.
Why it happens
A chain rolls a new number for every entry, and an entry is only reached when every roll before it failed. Spirit Grass is only checked when Common Herb missed, half of the time, so it gets 30% of 50%: 15%. Nothing drops when all four miss: 50% × 70% × 85% × 95% is about 28%. rand_weighted() rolls once over the total of all weights, so each entry gets exactly its share. If you want a chance of no drop, put it in the table as its own entry.
What to change
- The table: any number of entries, any weights. Use
0to switch an entry off without removing it. rng: one generator per system keeps loot rolls separate from other random things.
Chances that miss too many times in a row: pseudo-random chance. Recipes that work in any order: crafting recipe check.
A ready-made system: Xianxia Alchemy & Pill Refining System for Godot 4 has herbs, recipes, a furnace heat minigame, experimenting to discover recipes, levels and save/load.
Tested in Godot 4.7 with the Compatibility renderer.
Ready-made: Xianxia Alchemy & Pill Refining System for Godot 4 has herbs, recipes, a furnace heat minigame, experimenting to discover recipes, levels and save/load.
More how-tos: Game systems
- Hover a 3D object inside a SubViewport
- A turned building that covers the cells it stands on
- An inventory that never loses an item and never overfills a stack
- A JSON save that loads back exactly what you saved
- Fire that spreads one cell per step, in every direction
- A pooled enemy that comes back as fresh as a new one
- An enemy that stops at the dead player and finds the respawned one
- Poison, burn and bleed that keep ticking when applied again
- XP, qi and gold that keep growing without going negative
- Count slot line wins with wilds in front
- Random directions spread evenly over a sphere or a cone
- Count a lap only when the car really went round
- Make a seed repeat: daily runs, replays and roguelike seeds
- Offline progress that counts the time the game was closed
- A chance roll without the long bad-luck streaks
- Check crafting recipes in any order, with the right counts
- Make HP and mana regen the same at any frame rate
- Damage over time with the right number of ticks
- Spawn enemies where the camera cannot see them
- Keep a chasing horde from stacking into one enemy
- Make the fish bite after the same wait at any frame rate
- Snap buildings to the right grid cell on both sides of the origin
- Make a cooking timer fire once, on time
- Level up as many times as the XP covers
- Walk a patrol guard to each point without overshooting
- Remove items from an Array while checking them, without skipping any
- Scatter spikes, roots or trees in a circle without overlaps
- Count and take crafting items from every stack
- Play random sounds and events without obvious repeats
- Pick the growth image so the ripe one shows exactly when the crop can be picked
- Turn a day counter into season, day and year without a day 0
- An enemy that dies once, however many hits land
- A fair shuffle you can replay
- A ghost that drives the lap at real speed
- A vision cone that does not flicker at the edge
- Move a group of units without a pile-up
- A sprinkler that waters a round patch
- A slot reel that always lands forward on the result
- A crowd of NPCs that never emote or bob in step
- A song position that moves on every frame
- Nodes your editor tool adds that stay in the scene