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.
- Create a random number generator
- 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:
1 2 3 |
let randomGenerator = GKRandomDistribution(lowestValue: 1, highestValue: 6) |
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:
1 2 |
let dieRoll = randomGenerator.nextInt() |
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.