Search code examples
ioscocos2d-iphonecgpointarc4random

Randomly choose between predetermined CGPoints?


I have three pre determined spawnpoints in my game that I have stored into CGPoints ivars

CGPoint spawnPos1 = ccp(50, 50);
CGPoint spawnPos2 = ccp(150, 150);
CGPoint spawnPos3 = ccp(250, 250);

What I would like to do is randomly choose between these points. After that I will set the position of my sprites to that point. Can I use arc4random somehow?

I have seen tons of examples on generating random points and I already do that in my game, but I am drawing a blank on how to use the predetermined points? Any suggestions would be greatly appreciated?

So from the init method I call [self createSpawnPoint]; where I have these three points and in there I will set it to spawnPoint, which is just a ivar that I will use to set my sprites in a different method.

Thanks in advance!


Solution

  • Just use arc4random() % 3 to choose which value:

    int spawnChoice = arc4random() % 3;
    CGPoint spawnPoint = CGPointZero;
    
    if(spawnChoice == 0){
      spawnPoint = CGPointMake(50.0, 50.0);
    }
    else if(spawnChoice == 1){
      spawnPoint = CGPointMake(150.0, 150.0);
    }
    else{
      spawnPoint = CGPointMake(250.0, 250.0);
    }
    

    Hope that Helps!