-1

Possible Duplicate:
Generating Random Numbers in Objective-C

Hi I am creating an app where when you press a pimple it travels to a random place in the view. THe pimple is a UIImageView. Here is the code that I put in:

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

This code: pimple.center = CGPointMake(random(), random()); does not work. When I press the pimple, the pimple dissapears. Since I have not stated any .hidden for the pimple it must mean it IS moving. But you cant see it, (its outside the view.) Is there something wrong with my code? Am i missing something? Please help.

4

1 回答 1

2

afaik random() ist just the same as rand() in c which

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.

As a result you move our pimple to a random position inside a rect that is much bigger than your window. Try this: (I assume that self is a UIView)

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

The %-Operator is the Modulo-Operator.

It seems that you dont seed your pseudo-random-generator which leeds to always the same trajectory on each startup. There is another Thread on stackoverflow which tells us to use arc4random instead of random()/rand()

于 2011-05-30T09:23:51.603 回答