0 votes
var random = RandomNumberGenerator.new()

func ready():
random.randomize()
var n = random.randi
range(1, 100)

How would I code for it to check the randomly generated value and decide whether to drop the item or not based on a drop chance? Sorry I'm very new to all of this and just trying my best to learn as I go. I have checked out a bunch of resources I could find on using RNG + Arrays in Godot but I'm not quite sure how to code it out for myself. Also, I figured using an array might be redundant since I will only have 1 item on my drop table? But perhaps if I wanted to add more items later down the line it would be useful to just use arrays anyway. Any advice appreciated.

Godot version 3.3.2
in Engine by (17 points)

1 Answer

+1 vote
Best answer

For a simple case, use

func _ready():
  randomize()

var probability : int = 10 # 1/10 chance
if (randi() % probability) == (probability - 1): 
  it_happened() # do something 

For a multiple items (Array) I suggest you need two answers: whether you want to drop something at all (use example above) and if it happens, check which one

var items = ["First", "Second", "Third"] # your items

# first check if items exist, actually should be done before first query
if items.size() > 0 : 
  var idx : int = randi() % items.size() # item index
  var item = items[idx] # do something with item
  items.remove(idx) # at least remove it from array
by (1,438 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.