Objective random numbers C

I'm new to Objective-C, and for starters, I'm making a simple pong game.

To make the ball move at the beginning of a new round, I use

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

However, the important part is precisely this:

4 - arc4random() % 8

However, there are several problems with this: in the first place, it really does not generate a random number. Only after I leave the simulator, then again open new numbers. Secondly, I want it to generate numbers between -4 and -2 or 2 and 4.

I look here and elsewhere for an hour and still can't find anything. I'm so used to PHP where it is much easier.

Thank. Again, I looked at other issues here, and the suggestions they give do not work as I want, or just confuse me.

+3
source share
3 answers

arc4random() iphone, rand(). arc4random() .

:

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

rand(). , "" , , , .

, , arc4random.

+3

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 the following:

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;
0
source

Source: https://habr.com/ru/post/1791912/


All Articles