Hey guys. I didn't know where better to put this, so I thought General was probably a good place. Below is the terrain algorithm I came up with for generating 2D terrain - it uses midpoint displacement, and I'm sure it's totally inefficient (feel free to post any improvements you make!)
- but it does work (I need to clean up the random side of things a little more, it's not as clever as I would like).
Anyway, enjoy. Things you need to know: terrain is defined globally in my test program, as a std::list\ - you can pretty much move that wherever you want it, I've been thinking about turning all this terrain stuff into a class, but I haven't progressed far enough with that yet. The iterations parameter for MakeTerrain() simply controls how many times it loops over, adding more points as it goes, and the roughness parameter sort of controls how much the random range is reduced each time through the loop (basically, the higher the value, the less big spikes you will see in your terrain).
Here's the code:
void MakeTerrain( int iterations, double roughness )
int max_range = 127;
// both of these will be random later
terrain.push_back( (float)(rand() % (max_range * 2) - max_range )); // start point
terrain.push_back( (float)(rand() % (max_range * 2) - max_range )); // end point
int insertions = 1;
for( int a = 0; a < iterations; a++ )
for( int b = 0; b < insertions; b++ )
list<float>::iterator vIndex = terrain.begin();
for( int c = 0; c < (b*2); c++ )
float pointA = *vIndex;
float pointC = *vIndex;
// calculate new point, inserted at vIndex
terrain.insert( vIndex, ((pointA + pointC) / 2) + rand() % (max_range * 2) - max_range );
insertions *= 2;
// change the max range of the random alteration
max_range *= roughness;
I wish this thing accepted tabs properly Oh, and thanks to Ed Mack for help with the averaging of the point values, I'd never have gotten it to a working state otherwise.
you know you can submit this here for a code spotlight.
Right, I hadn't noticed that I'll do that now.