生成噪声图

生成噪声图

确定某一位置的地形类型。

    private float [,] GenerateNoiseMap(int width,int height,float lacunarity,int seed)
    {   
        //使用随机数种子
        Random.InitState(seed);
        lacunarity += 0.1f;

        //噪声图为顶点服务要 -1
        float[,] noiseMap = new float[width - 1,height - 1];
        float offsetX = Random.Range(-10000f, 10000f);
        float offsetY = Random.Range(-10000f, 10000f);
        for (int x = 0; x < width - 1; x++)
        {
            for (int y = 0; y < height - 1; y++)
            {
                noiseMap[x, y] = Mathf.PerlinNoise(x * lacunarity + offsetX, y * lacunarity + offsetY);

            }
        }
        return noiseMap;
    }

注意噪声图为顶点服务,确定某一点的地形后在其周围生成对应的地形的格子,索引区间长度和顶点一致是n-1,但噪声图索引范围是[0,map.weight/height - 2],顶点是[1,map.weight/height - 1]。

补充GenerateMap逻辑。

    public void GenerateMap()
    {   
        //生成Mesh
        meshFilter.mesh = GenerateMapMesh(mapHeight, mapWidth, cellSize);

        //生成网格
        grid = new MapGrid(mapHeight, mapWidth, cellSize);

        //生成噪声图
        float [,] noiseMap = GenerateNoiseMap(mapWidth, mapHeight, lacunarity, seed);

    }

优化顶点、格子生成边界判定

    public MapCell GetCell(Vector2Int index)
    {
        MapCell cell = null;
        cellDic.TryGetValue(index, out cell);
        return cellDic[index];
    }

    public MapVertex GetVertex(Vector2Int index)
    {
        MapVertex vertex = null;
        vertexDic.TryGetValue(index, out vertex);
        return vertex;
    }

避免额外一次ContainsKey判断key是否而存在,若给定关键字不在字典中返回Null。