简体   繁体   English

使用柏林噪声在 C# 中生成地形

[英]Generating terrain in C# using perlin noise

I'm working on civilization game in C# and XNA.我正在用 C# 和 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.谢谢你。

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.请注意,如果您需要不止 3 次通过,您可以添加一个循环和值数组。

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.您可以添加更多内容,我添加了更多随机性并将一些图块向上或向下缩进 1 以获得更好的地形。 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.尝试使用 2D Perlin Noise算法,并选择特定高度来制作洞穴和更高级的地形,因为这就是我现在所做的,但这里的代码是一个好的开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM