Random Numbers in GDScript
Our random number generation example demonstrates how to generate pseudorandom numbers in GDScript.
In GDScript, we use built-in functions for random number generation. The randi()
function generates random integers, while randf()
generates random floats between 0 and 1.
For generating random integers within a specific range, we use the modulo operator (%
) with randi()
. For example, randi() % 100
gives a random integer between 0 and 99.
The randf_range(from, to)
function is used to generate random floats within a specific range.
To create a random number generator with a fixed seed, we use the RandomNumberGenerator
class. This allows us to generate reproducible sequences of random numbers.
When you run this script, you might see output similar to this:
Note that the actual numbers may be different each time you run the script, except for the last two lines which use a fixed seed.
GDScript’s random number generation is suitable for most game development needs. For more advanced randomization techniques or cryptographically secure random numbers, you might need to implement custom solutions or use external libraries.
Remember that the random number generation in GDScript, like in most programming languages, is pseudorandom. For truly random numbers, you would need to use hardware random number generators or external sources of entropy.