Unity自用工具:基于种子与地块概率的开放世界2D地图生成

public class BuildingGen : MonoBehaviour
{
    public int[] Building;//存储要生成的地块代码
    public int[] Probability;//存储概率
    public double seed;

    public int width = 100;
    public int height = 100;
    public float noiseScale = 0.1f;  //噪声缩放倍数

    private int[,] frequencyMap;//存储柏林噪声生成的二维数组

    void Start()
    {
        frequencyMap = new int[width, height];

        GeneratePerlinNoise();
       //在这里根据需要补一个根据frequencyMap生成地块的代码
    }

    private void GeneratePerlinNoise()
    {
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                float xCoord = (float)x / width * noiseScale;
                float yCoord = (float)y / height * noiseScale;
                
                float perlinValue = Mathf.PerlinNoise((float)xCoord + (float)seed, (float)yCoord + (float)seed);

                int buildingType = MapPerlinValueToBuildingType(perlinValue);

                frequencyMap[x, y] = buildingType;
            }
        }
    }

    private int MapPerlinValueToBuildingType(float perlinValue)
    {
        float cumulativeProbability = 0;

        for (int i = 0; i < Probability.Length; i++)
        {
            cumulativeProbability += (float)Probability[i] / 100.0f;

            if (perlinValue <= cumulativeProbability)
            {
                return Building[i];
            }
        }

        return Building[Building.Length - 1];
    }
}

实机效果:通过修改seed以生成不同的地形

Unity自用工具:基于种子与地块概率的开放世界2D地图生成_第1张图片Unity自用工具:基于种子与地块概率的开放世界2D地图生成_第2张图片

修改地块权重让绿色地块更多:

Unity自用工具:基于种子与地块概率的开放世界2D地图生成_第3张图片

你可能感兴趣的:(unity,java,游戏引擎)