2011-05-30 93 views
-1

可能重複:
Generating Random Numbers in Objective-CCGPointMake(隨機(),隨機())不工作

嗨,我創建就是當你按下一個疙瘩再轉移到一個隨機的應用放置在視圖中。疙瘩是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(隨機(),隨機());不起作用。當我按下疙瘩時,疙瘩消失。由於我沒有提到任何隱藏的疙瘩,它必定意味着它在移動。但是你不能看到它(它在視圖外部)。我的代碼有什麼問題嗎?我錯過了什麼嗎?請幫忙。

回答

2

AFAIK隨機()北京時間只是一樣蘭特(c)中其中

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); 

的% - 運算符是Modulo-Operator

看起來,你不會給你的僞隨機發生器種子,這種發生器在每次啓動時總是使用相同的軌跡。有another Thread on stackoverflow告訴我們使用arc4random而不是random()/ rand()