Randomly generated tunnel walls that don't jum

2019-02-20 12:28发布

问题:

I'm generating a sort of tunnel that you can fly through, in a 2D screen. I want the walls to smoothly move from left to right randomly. Right now I just end up with "spikes".

I want it to look like this

instead of this

I'm using code for the walls that looks like this, forty times each left and right.

if (Left1.center.y > 568) {
    RandomPosition = arc4random() %55;
    Left1.center = CGPointMake(RandomPosition, 0);
    RandomPosition = RandomPosition + 265;
    Right1.center = CGPointMake(RandomPosition, 0);
}

and then this

RandomPosition = arc4random() %55;
Left1.center = CGPointMake(RandomPosition, 0);
RandomPosition = RandomPosition + 265;
Right1.center = CGPointMake(RandomPosition, 0);

but it doesnt really move the walls the way I want.

回答1:

What you're looking for is called "correlated" random number generation.

One of the most popular ways of generating such numbers is called Perlin noise, which may be too complicated for your needs.

The simplest thing to do in your case would be to keep track of the last wall position, and generate a random offset from that, instead of the number generator being used for the bare value of the wall. This is known as a "random" or "drunken" walk.

To keep the tunnel's width the same, randomly pick only the left wall's end point, then put the right wall's end the correct distance away.

CGFloat leftWallX = /* starting value */;
for( int i = 0; i < NUM_WALLS; i++ ){
    // Generate a number from -MAX_OFFSET to MAX_OFFSET
    CGFloat offset = (CGFloat)arc4random_uniform(2*MAX_OFFSET) - MAX_OFFSET;
    leftWallX += offset;
    rightWallX = leftWallX + tunnelWidth;
    //...
}