Unity简单的高度图生成地形
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;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
var color = HeightMap.GetPixel(x, y);
allVertexs = 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 = x * width + y;
allIndices = (x + 1) * width + y + 1;
allIndices = (x + 1) * width + y;
allIndices = x * width + y;
allIndices = x * width + y + 1;
allIndices = (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;
页:
[1]