How do you make something happen with a certain percentage?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By dezekeerjoran
:warning: Old Version Published before Godot 3 was released.

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

:bust_in_silhouette: Reply From: Nutr1z

Hi,

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

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

sorry, but it doesn’t work.

dezekeerjoran | 2017-01-03 21:57

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

Nutr1z | 2017-01-04 08:27

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

dezekeerjoran | 2017-01-06 19:16

:bust_in_silhouette: Reply From: eons

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.