Generating terrain in C# using perlin noise

寵の児 提交于 2019-12-11 14:12:40

问题


I'm working on civilization game in C# and XNA. I use a two dimensional integer array, populated with a loop, to generate tiles, I've done a ton research and have been unable to find a way to generate earth like terrain. Can anyone explain how to do this or at least give me code that could do it, though I would prefer and explanation? Thank you.


回答1:


I use an algorithm similar to this to make my terrain. Basicly it generates some random numbers and uses a sine wave to generate hills, when combined they give a nice hilly landscape. Note that you can add a loop and array of values if you want more than just 3 passes.

private void GenerateTerrain()
    {
        terrainContour = new int[Width*Height];

        //Make Random Numbers
        double rand1 = randomizer.NextDouble() + 1;
        double rand2 = randomizer.NextDouble() + 2;
        double rand3 = randomizer.NextDouble() + 3;

        //Variables, Play with these for unique results!
        float peakheight = 20
        float flatness = 50 
        int offset = 30;


        //Generate basic terrain sine
        for (int x = 0; x < Width; x++)
        {

            double height = peakheight / rand1 * Math.Sin((float)x / flatness * rand1 + rand1);
            height += peakheight / rand2 * Math.Sin((float)x / flatness * rand2 + rand2);
            height += peakheight / rand3 * Math.Sin((float)x / flatness * rand3 + rand3);

            height += offset;

            terrainContour[x] = (int)height;
        }
    }

Then to fill the heightmap just loop through the values and check if it is above the threshold or not.

for (int x = 0; x < Width; x++)
{
   for (int y = 0; y < Height; y++)
   {

       if (y > terrainContour[x])
           tiles[x, y] = Solid Tile
       else
           tiles[x, y] = Blank Tile
   }
}

Theres much more you can add to it, I've added more randomness and indenting some tiles by 1 up or down for better terrain. And adding more sine waves will make it more realistic.

Try using 2D Perlin Noise algorithms, and selecting certain heights to make caves and more advanced terrain, as this is now what I do, but this code here is a good start.



来源:https://stackoverflow.com/questions/9697079/generating-terrain-in-c-sharp-using-perlin-noise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!