问题描述
我正在用 C# 和 XNA 开发文明游戏.我使用一个二维整数数组,填充了一个循环,来生成瓦片,我做了大量的研究,但一直无法找到一种生成类似地球的地形的方法.任何人都可以解释如何做到这一点或至少给我可以做到这一点的代码,尽管我更喜欢和解释?谢谢.
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.
推荐答案
我使用与此类似的算法来制作地形.基本上它会生成一些随机数并使用正弦波来生成山丘,当它们结合在一起时,它们会产生漂亮的丘陵景观.请注意,如果您需要 3 次以上的传递,您可以添加一个循环和值数组.
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
}
}
您可以添加更多内容,我添加了更多随机性并将一些图块向上或向下缩进 1 以获得更好的地形.添加更多正弦波会使其更逼真.
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.
尝试使用 2D Perlin Noise 算法,并选择特定高度制作洞穴和更高级的地形,因为这就是我现在所做的,但这里的代码是一个好的开始.
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.
这篇关于使用柏林噪声在 C# 中生成地形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!