CGPointMake(random(),random())不起作用

时间:2011-05-30 08:58:05

标签: objective-c random cgpoint

  

可能重复:
  Generating Random Numbers in Objective-C

您好我正在创建一个应用程序,当您按下疙瘩时,它会移动到视图中的随机位置。疙瘩是一个UIImageView。这是我输入的代码:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *myTouch = [touches anyObject];

    CGPoint point = [myTouch locationInView:pimple];
    if ( CGRectContainsPoint(pimple.bounds, point) ) {
        [self checkcollision];
    }
}

-(void)checkcollision 
{

    pimple.center = CGPointMake(random(), random());    
    sad.hidden = NO;    
    NSURL* popURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"pop" ofType:@"mp3"]];
    AudioServicesCreateSystemSoundID((CFURLRef) popURL, &popID);
    AudioServicesPlaySystemSound(popID);
}

此代码:pimple.center = CGPointMake(random(),random());不起作用。当我按压疙瘩时,疙瘩消失了。因为我没有说过任何.hidden的疙瘩,它必须意味着它正在移动。但是你无法看到它(它在视图外面。)我的代码有问题吗?我错过了什么吗?请帮忙。

1 个答案:

答案 0 :(得分:2)

afaik random()与c中的rand()相同

  

Returns a pseudo-random integral number in the range 0 to RAND_MAX. [...] RAND_MAX is a constant defined in cstdlib. Its default value may vary between implementations but it is granted to be at least 32767.

因此,您将我的疙瘩移动到比窗口大得多的矩形内的随机位置。试试这个:(我认为自我是一个UIView)

pimple.center = CGPointMake(
    random() % (unsigned int)self.bounds.size.width, 
    random() % (unsigned int)self.bounds.size.height);

%-Operator是Modulo-Operator

似乎你没有为你的伪随机发生器播种,它们在每次启动时都会出现相同的轨迹。有another Thread on stackoverflow告诉我们使用arc4random而不是random()/ rand()