3

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Gus
  • 1,905
  • 6
  • 23
  • 37

3 Answers3

9

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;
Bogatyr
  • 19,255
  • 7
  • 59
  • 72
  • The rand() function generates smaller numbers (int - less unique), the longer alternative is random() that generates more unique numbers (long). Both are performance efficient as they are seeded only once. The right place to use rand() is mainly in while loops with intensity of thousands requests for random number per second. The arc4random() does not need any seeding, it automatically initializes itself what cost some performance for uniqueness. It is preferred in non frequent calls (tens per second). – jold Apr 28 '15 at 08:48
3

You need to look at the rand() function. Basically, you "seed" it with a start value, and it returns a new random number every time you call it.

Or look at this question which has a full example using arc4random.

Community
  • 1
  • 1
Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
  • I tried rand() with seeding, and it would still generate the same random number, even if I re-called srand(time(NULL)) as well. I also looked at that question and I think that's what I'm already doing. – Gus Feb 14 '11 at 03:51
0

This will give you a floating point number between -4 and -2 OR 2 and 4

float low_bound = -4; //OR 2      
float high_bound = -2;//OR 4
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);

If you want a number in -4…-2 AND 2…4 try this:

float low_bound = 2;      
float high_bound = 4;
float rndValueTemp = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
float rndValue = ((float)arc4random()/0x100000000)<0.5?-rndValueTemp:rndValueTemp;
Tibidabo
  • 21,461
  • 5
  • 90
  • 86