本帖最后由 西北旺 于 2018-11-23 18:19 编辑
unity提供了动态绘制模型的接口,在需要动态建模的程序中,可以利用这个接口,动态绘制出模型。
1.获取组件meshfilter,Mesh mesh=GetComponent<MeshFilter>().mesh;
2.获取模型的轨迹数据,一般为用户层传入;
2.对mesh的顶点数据、索引数据、法线数据、UV数据等赋值,即可按轨迹动态绘制出片状模型;
主要代码如下:
[mw_shl_code=csharp,true]//根据链表创建数组
Vertices_Count = VertexList.Count;
Vector3[] vertices = new Vector3[Vertices_Count];
//根据三角形个数创建索引数组
int triangles_count = Vertices_Count - 2;
int[] triangles = new int[triangles_count * 3];
//创建UV数组
Vector2[] uv = new Vector2[Vertices_Count];
for (int i = 0; i < Vertices_Count; i++)
{
//顶点赋值
vertices = VertexList;
//UV赋值
if (i % 2 == 0)
{
uv = new Vector2(i * 0.5f * 1.0f / (Vertices_Count * 0.5f - 1.0f), 0);
}
else
{
uv = new Vector2(i * 0.5f * 1.0f / (Vertices_Count * 0.5f - 1.0f), 1);
}
}
//法线赋值
Vector3[] normals = new Vector3[Vertices_Count];
for (int i = 0; i < Vertices_Count; i++)
{
//给边缘的四个点及中间的两排顶点分别进行法线赋值
if (i == 0)
{
normals[0] = Vector3.Cross(vertices[1] - vertices[0], vertices[2] - vertices[0]).normalized;
}
else if (i == 1)
{
Vector3 temp2 = Vector3.Cross(vertices[3] - vertices[1], vertices[2] - vertices[1]).normalized;
normals[1] = (normals[0] + temp2) * 0.5f;
}
else if (i == (Vertices_Count - 1))
{
normals[Vertices_Count - 1] = Vector3.Cross(vertices[Vertices_Count - 2] - vertices[Vertices_Count - 1], vertices[Vertices_Count - 3] - vertices[Vertices_Count - 1]).normalized;
}
else if (i == (Vertices_Count - 2))
{
Vector3 temp1 = Vector3.Cross(vertices[Vertices_Count - 2] - vertices[Vertices_Count - 1], vertices[Vertices_Count - 3] - vertices[Vertices_Count - 1]).normalized;
Vector3 temp2 = Vector3.Cross(vertices[Vertices_Count - 4] - vertices[Vertices_Count - 2], vertices[Vertices_Count - 3] - vertices[Vertices_Count - 2]).normalized;
normals[Vertices_Count - 2] = (temp1 + temp2) * 0.5f;
}
else if (i % 2 == 0)
{
Vector3 temp1 = Vector3.Cross(vertices[i - 2] - vertices, vertices[i - 1] - vertices).normalized;
Vector3 temp2 = Vector3.Cross(vertices[i + 1] - vertices, vertices[i + 2] - vertices).normalized;
Vector3 temp3 = Vector3.Cross(vertices[i - 1] - vertices, vertices[i + 1] - vertices).normalized;
normals = (temp1 + temp2 + temp3) / 3;
}
else if (i % 2 == 1)
{
Vector3 temp1 = Vector3.Cross(vertices[i - 1] - vertices, vertices[i - 2] - vertices).normalized;
Vector3 temp2 = Vector3.Cross(vertices[i + 1] - vertices, vertices[i - 1] - vertices).normalized;
Vector3 temp3 = Vector3.Cross(vertices[i + 2] - vertices, vertices[i + 1] - vertices).normalized;
normals = (temp1 + temp2 + temp3) / 3;
}
}
meshfront.vertices = vertices;
meshfront.normals = normals;
meshfront.uv = uv;
//给索引赋值
int j = 0;
for (int i = 0; i < triangles_count * 0.5; i++)
{
triangles[j++] = 2 * i + 0;
triangles[j++] = 2 * i + 1;
triangles[j++] = 2 * i + 2;
triangles[j++] = 2 * i + 3;
triangles[j++] = 2 * i + 2;
triangles[j++] = 2 * i + 1;
}
meshfront.triangles = triangles;[/mw_shl_code]
效果如下:
效果演示
|