Dragonfly Cloud announces new enterprise security features - learn more

Question: How do you generate a random number in GameMaker?

Answer

GameMaker Studio offers several functions to generate random numbers, which can be used for a variety of purposes such as randomizing game events, generating procedural content, or just picking a random value within a specific range. Here's how you can use these functions:

  1. irandom(n): This function will return a random integer between 0 and n, with n included. For example, if you want a random integer between 0 and 10:
var randomNumber = irandom(10);
  1. irandom_range(min, max): Similar to irandom(n), but lets you specify both a minimum and a maximum integer value. So, for an integer between 5 and 15:
var randomNumber = irandom_range(5, 15);
  1. random(n): Returns a random floating-point number between 0 and n, not including n itself. If you require a float between 0 and 5:
var randomNumber = random(5);
  1. random_range(min, max): Gives a random floating-point number in the range of min to max. Unlike irandom_range, both min and max can be non-integer values. To get a float between 2.5 and 7.5:
var randomNumber = random_range(2.5, 7.5);

Seeding Random Numbers

If you want to ensure that the same sequence of random numbers is generated each time your game runs, you need to set the seed using random_set_seed(seed) or randomize().

  • random_set_seed(seed): Sets the seed for random number generation to a specific value.
random_set_seed(12345); // Replace 12345 with your chosen seed number
  • randomize(): Sets the seed to a random value based on the current time.
randomize();

Using randomize() at the start of your game is a good way to make sure that the random numbers are less predictable and different every time you run your game.

Important Considerations

  • The random functions in GameMaker are deterministic, meaning they will produce the same sequence of numbers for a given seed.
  • Always remember to use randomize() at the start of the game if you want unique random sequences per game session, otherwise, the sequence will repeat every time you run the game if the seed stays the same.

These are the basics of using random numbers in GameMaker. Depending on what you're trying to achieve, these functions can be incredibly powerful tools in adding unpredictability and variation to your games.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost