0

I'm making a game where a player moves across platforms of differing heights with different distances between each one. Since I want the game to be different every time, I've written code to automatically generate the "ice" that the player has passed to a position in front of the player.

float viewHeight = self.view.bounds.size.height;
float fViewHeightMinusIceHeight = viewHeight – 55.0f;
int iViewHeightMinusIceHeight = (int)fViewHeightMinusIceHeight;

if (ice.center.x >= (self.view.bounds.size.width + 8)) 
    {
    float y = random() %iViewHeightMinusIceHeight;
    y = y + 22.5f;
    float x = (random() % 20) – 8;
    ice.center = CGPointMake(x,y);
    }

This is only one of the objects. The same code is used for ice1, ice2, etc.

This generates the objects just fine. The first problem is that I would like to constrain the possibilities to only reasonable outcomes (e.g. no huge gaps), so that players can move from object to object.

The second problem is that sometimes the objects generate on top of one another.

j0409
  • 127
  • 1
  • 7
  • possible duplicate of [How to create random numbers from 4 to 10](http://stackoverflow.com/questions/18262895/how-to-create-random-numbers-from-4-to-10) – jscs Mar 05 '14 at 19:30
  • Take a look at my answer here: http://stackoverflow.com/a/17193450/1075405 – Groot Mar 05 '14 at 21:42

1 Answers1

0

It seems like a simple min/max for your range would be ideal. Something to the effect of:

#define kMinDistanceBetween 10
#define kMaxDistanceBetween 20

int variance = kMaxDistanceBetween - kMinDistanceBetween;
float xPosition = (float)(kMinDistanceBetween + arc4random_uniform(variance));

arc4random_uniform() returns a random int within the upper bound you pass. So you just make the X position your minimum + a random amount based on the min/max rule you set. I set it up as #defines so you can modify the rules in one place. You have to cast as float because arc4random_uniform() returns an int.

Eric G
  • 1,429
  • 18
  • 26