Dragonfly

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(12345); // Replace 12345 with your chosen seed number
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

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?

Other Common Game Engines Questions (and Answers)

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