Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Random Numbers

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.

like image 867
Gus Avatar asked Feb 17 '26 18:02

Gus


2 Answers

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;
like image 74
Bogatyr Avatar answered Feb 19 '26 06:02

Bogatyr


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.

like image 38
Charlie Martin Avatar answered Feb 19 '26 08:02

Charlie Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!