+1 vote

How do you make something happen? But there is a percentage that the event happens.

in Engine by (55 points)

2 Answers

+4 votes

Hi,

You can use math random methods like randf(), see gdscript-randf

var percent = randf()
if (percent > 0.8):
    # some coode
by (370 points)

sorry, but it doesn't work.

If you don't explain what doesn't work, we can't help you. eons on the answer has a better explain but the principle is same. randf() generate a float between 0 and 1 and the if allow the code bellow to be executed only if superior to 0.8 = 20 percent of chance to be exectued

sorry, thanks, it does work. Forgot to put randomize() before it.

+3 votes

The common way to do it is using a random number generator, in the case of GDScript, "randf()" is the best for this.

With that function you will get a random number between 0 and 1, you can take 0 as 0% and 1 as 100%.

That way, dividing the range 0 to 1 in percentile-like fashion you can make decisions according the result of the generator.


Example: if you have 30% chances, check if the random number is <= 0.3(or > 0.7) .
There is a probability of 30% that the randf result in a number <= 0.3 (or > 0.7).

ps: remember to use randomize() somewhere before the use of random number generators.

by (7,946 points)
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 Frequently asked questions and 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 [email protected] with your username.