Generating Random Numbers in Swift with GameplayKit

Many games have a need to generate random numbers. If you are making an iOS game with SpriteKit, the GameplayKit framework has classes for generating random numbers.

Generating random numbers has two steps.

  1. Create a random number generator
  2. Generate a random number

Creating a Random Number Generator

Create an instance of GKRandomDistribution, which is GameplayKit’s class for generating random numbers. Supply the low and high values to define the range of numbers the generator can generate.

The following code demonstrates how to create a random number generator for rolling a die:

Generating a Random Number

After creating the random number generator, you can use it to generate random numbers. Call the generator’s nextInt function to generate a random number.

The following code simulates a die roll:

Example

I have a simple game prototype on GitHub that spawns objects at random starting points.

The spawnFood function in the GameScene.swift file has the random number code.