3

我正在制作一个简单的乒乓球游戏。为了让球在新一轮开始时移动,我正在使用

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

然而,重要的部分是这样的:

4 - arc4random() % 8

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

4

3 回答 3

9

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

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

int minus2_to_minus4 = (arc4random() % 3) - 4;
int two_to_four = (arc4random() % 3) + 2;
于 2011-02-14T06:19:19.773 回答
3

您需要查看rand()功能。基本上,你用一个起始值“播种”它,每次你调用它时它都会返回一个新的随机数。

或者看看这个问题,它有一个使用 arc4random 的完整示例。

于 2011-02-14T03:36:03.427 回答
0

这将为您提供介于 -4 和 -2 或 2 和 4 之间的浮点数

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

如果您想要 -4…-2 AND 2…4 中的数字,请尝试以下操作:

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;
于 2012-03-04T00:28:45.083 回答