GTG101 GTG101 - 2 years ago 119
Swift Question

Creating random number in SpriteKit

I'm trying to create a game in which a projectile is launched at a random angle.
To do this I need to be able to generate two random Int's. I looked up some tutorials and came up with this:

var random = CGFloat(Int(arc4random()) % 1500)
var random2 = CGFloat(Int(arc4random()) % -300)
bullet.physicsBody!.velocity = CGVectorMake((random2), (random))

It worked for a while but now it just crashes.

Any help would be appreciated.

Answer Source

What I find I use the most is arc4random_uniform(upperBound) which returns a random Int ranging from zero to upperBound -1.

let random = arc4random_uniform(1500)
let random2 = arc4random_uniform(300) * -1

//pick a number between 1 and 10
let pick = arc4random_uniform(10)+1

The lowdown on the arc4 functions: arc4random man page

GameplayKit has a nice class wrapping the arc4 functions: GameplayKit Randomness

and a handy reference: Random Hipster

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download