Objective-C Random Numbers

Gus picture Gus · Feb 14, 2011 · Viewed 7.7k times · Source

I'm making a simple pong game. To make the ball move at the beginning of a new round, I am using

ballVelocity = CGPointMake(4 - arc4random() % 8,4 - arc4random() % 8);

However, the important part is just this:

4 - arc4random() % 8

However, there are a few problems with this: first and foremost, it doesn't really generate a random number. Only after I quit the simulator, then reopen it are new numbers generated. Secondly, I only want it to generate numbers between -4 and -2 or 2 and 4.

Answer

Bogatyr picture Bogatyr · Feb 14, 2011

arc4random() is the preferred random function on the iphone, instead of rand(). arc4random() does not need seeding.

This code will generate the ranges you're interested in:

int minus2_to_minus4 = (arc4random() % 3) - 4;
int two_to_four = (arc4random() % 3) + 2;