找回密码
 立即注册
查看: 178|回复: 0

Unity简单的高度图生成地形

[复制链接]
发表于 2022-12-23 19:18 | 显示全部楼层 |阅读模式

Terrain的生成有几种,这里为了后续的一些工作,我需要自己去生成类似Terrain的mesh,这里就简单记录一下;
其实原理很简单

  • 建立和高度图像素大小一样的顶点矩阵
  • 将高度图设置为R16
  • 将高度图的R通道,读取到坐标点的高度
  • 将顶点矩阵设置三角面
一下是简单的代码:
void GenerateTerrain()
    {
        if (HeightMap == null)
            return;
        Debug.Assert(HeightMap.format == TextureFormat.R16, "只支持R16");
        width = HeightMap.width;
        height = HeightMap.height;
        allVertexs=new Vector3[width * height];
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                var color = HeightMap.GetPixel(x, y);
                allVertexs[width * x + y] = new Vector3(x * SizeScale, color.r * HeightScale, y * SizeScale);
            }
        }
        // indices
        allIndices = new int[(width * height - width - height + 1) * 6];
        int index = 0;
        for (int x = 0; x < width-1; x++)
        {
            for (int y = 0; y < height-1; y++)
            {
                allIndices[index++] = x * width + y;
                allIndices[index++] = (x + 1) * width + y + 1;
                allIndices[index++] = (x + 1) * width + y;

                allIndices[index++] = x * width + y;
                allIndices[index++] = x * width + y + 1;
                allIndices[index++] = (x + 1) * width + y + 1;
            }
        }
        mesh = new Mesh();
        mesh.SetVertices(allVertexs);
        mesh.SetTriangles(allIndices, 0);
        mesh.RecalculateNormals();
    }
上面的代码要注意:unity默认的模型面数上限是 2^{16} ,所以建议注意一下大小(或者考虑使用lod和四叉树之类的)!
如果先要把这个限制开放大一点,可以将Mesh.indexFormat设置成32位。
mesh.indexFormat = IndexFormat.UInt32;

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-5-5 00:34 , Processed in 0.091803 second(s), 26 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表