Thanks Doge
Thanks Doge

Reputation: 183

seed random numbers Objective-C

I'm working on a game in Xcode 6 and need to generate a new random number each time 2 specific objects touch each other. I have tried using srand() at the start of my application but it seems that the values remain the same as if it isn't seeding a new value each time the objects collide.

here is the code

if((CGRectIntersectsRect(Stickman.frame, Box1.frame))) {
    xRan = arc4random()%11;

  if(xRan<=3){
        Spike1 = true;
        [self SpikeCall];
    }

    //Gold
    if (xRan==10) {
            G1 = true;
    }

Box1.center = CGPointMake(0,278);
Box1SideMovement = 5;      
}

The problem is that after the Stickman hits the Box1 when it comes back on screen it still holds the same value in xRan except for certain scenarios where it will between 1-3 then it makes Spike1 true. I'd like it to be so that each time the object Box1 intersects with Stickman the xRan seeds a new number between 1-10 so that there is a 1 in 10 chance of G1 becoming true & if xRan is 1-3 it will make Spike1 true.

Upvotes: 0

Views: 446

Answers (1)

Aaron Golden
Aaron Golden

Reputation: 7102

This is more of a comment than an answer, but it's too long for a comment.

There are a couple of problems with your approach here. First, srand does not seed the arc4random function. It seeds the rand function, which is a different pseudo-random number generator with somewhat worse properties than arc4random. There is no explicit seeding function for arc4random. Second, if you want a random number between 1 and 10 you should not use the % 11 approach. That gives you a random number between 0 and 10 (and I think you don't want zero), but also it probably does not give you a uniform distribution. Even if arc4random is good at providing a uniform distribution in its whole range it may not provide a uniform distribution of the least significant bits.

I suggest you use something like:

arc4random_uniform(10) + 1

arc4random_uniform(10) will return a number between 0 and 9, and will do a good job of providing a uniform distribution in that range. The +1 just shifts your interval so you get numbers between 1 and 10 instead of between 0 and 9.

Upvotes: 2

Related Questions