Objective-C随机数

Gus*_*Gus 3 random objective-c ios pong

我正在做一个简单的乒乓球比赛.为了让球在新一轮开始时移动,我正在使用

ballVelocity = CGPointMake(4 - arc4random() % 8,4 - arc4random() % 8);
Run Code Online (Sandbox Code Playgroud)

但是,重要的是这个:

4 - arc4random() % 8
Run Code Online (Sandbox Code Playgroud)

但是,这有一些问题:首先,它并不真正生成一个随机数.只有在我退出模拟器后,重新打开它才会生成新的数字.其次,我只希望它生成-4到-2或2到4之间的数字.

Bog*_*tyr 9

arc4random()是iphone上的首选随机函数,而不是rand().arc4random()不需要播种.

此代码将生成您感兴趣的范围:

int minus2_to_minus4 = (arc4random() % 3) - 4;
int two_to_four = (arc4random() % 3) + 2;
Run Code Online (Sandbox Code Playgroud)