基于每一个网格的贴图数值,生成对应的网格贴图。

    /// <summary>
    /// 生成地图贴图
    /// </summary>
    private Texture2D GenerateMapTexture(int[,] cellTexutreIndexMap, Texture2D groundTexture, Texture2D[] marshTextures)
    {
        //地图宽高
        int mapWidth = cellTexutreIndexMap.GetLength(0);
        int mapHeight = cellTexutreIndexMap.GetLength(1);

        //贴图都是矩形,得到每个格子像素大小
        int textureCellSize = groundTexture.width;

        //全图贴图像素大小
        Texture2D mapTexture = new Texture2D(mapWidth * textureCellSize, mapHeight * textureCellSize);

        //遍历每一个格子
        for (int y = 0; y < mapHeight; y++)
        {
            int offsetY = y * textureCellSize;
            for (int x = 0; x < mapWidth; x++)
            {
                int offsetX = x * textureCellSize;
                int textureIndex = cellTexutreIndexMap[x, y] - 1;
                //绘制每一个格子内的像素
                for (int y1 = 0; y1 < textureCellSize; y1++)
                {
                    for (int x1 = 0; x1 < textureCellSize; x1++)
                    {
                        //设置某个像素点的颜色
                        //确定是森林还是沼泽
                        //这个地方是森林 || 这个地方时沼泽但是透明的,需要绘制地面groundTexture同位置像素
                        if (textureIndex < 0)
                        {
                            //是森林,绘制GroundTexture
                            Color color = groundTexture.GetPixel(x1, y1);
                            mapTexture.SetPixel(x1 + offsetX, y1 + offsetY, color);
                        }
                        else
                        {
                            //是沼泽,绘制 marshTextures
                            Color color = marshTextures[textureIndex].GetPixel(x1, y1);
                            if (color.a == 0)
                            {
                                //沼泽是透明的,还是绘制森林
                                mapTexture.SetPixel(x1 + offsetX, y1 + offsetY, groundTexture.GetPixel(x1, y1));
                            }
                            else
                            {
                                mapTexture.SetPixel(x1 + offsetX, y1 + offsetY, color);
                            }
                        }
                    }
                }
            }
        }
        mapTexture.filterMode = FilterMode.Point;
        mapTexture.wrapMode = TextureWrapMode.Clamp;
        mapTexture.Apply();
        return mapTexture;
    }

一共四层循环逻辑,外面两层遍历每个格子,里面两层循环,遍历每个格子中的每个像素点,根据当前格子的贴图索引,如果是森林则绘制默认贴图,是沼泽需要绘制经过计算后叠加的贴图,如果对应格子内的像素点是透明的,代表这个点虽然归宿沼泽类型但并没有沼泽的内容,还是绘制下层的默认贴图。

        Texture2D mapTexture = GenerateMapTexture(celltexutreIndexMap, groundTexture, marshTextures);
        meshRenderer.sharedMaterial.mainTexture = mapTexture;

导入资源,测试贴图生成。

alt

最终效果,后续对地图进行分割,避免生成地图过大。