Unity3D之Mesh(三)绘制四边形
发表于2018-11-15
前面两篇文章给大家铺垫了三边形的介绍,这篇文章就延伸一下,给大家讲讲使用mesh绘制四边形。知识点其实都差不多,下面就用案例来帮助大家掌握这个知识点,并且能对大家以后有所帮助。

步骤:
1、创建一个empty 的gameobject;
2、添加一个脚本给这个game object;
具体脚本如下:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshRenderer), typeof(MeshFilter))]
public class quad : MonoBehaviour
{
/*
creat a triangle by using Mesh
2016/11/21
————Carl
*/
void Start()
{
creatQuad();
}
public float q_length = 3;
public float q_width = 2;
private void creatQuad()
{
/* 1. 顶点,三角形,法线,uv坐标, 绝对必要的部分只有顶点和三角形。
如果模型中不需要场景中的光照,那么就不需要法线。如果模型不需要贴材质,那么就不需要UV */
Vector3[] vertices =
{
new Vector3(0,0,0),
new Vector3(0,0,q_width),
new Vector3(q_length,0,q_width),
new Vector3(q_length,0,0),
};
Vector3[] normals =
{
Vector3.up,
Vector3.up,
Vector3.up,
Vector3.up
};
Vector2[] uv =
{
Vector2.zero,
-Vector2.left,
Vector2.one,
Vector2.right
};
/*2. 三角形,顶点索引:
三角形是由3个整数确定的,各个整数就是角的顶点的index。 各个三角形的顶点的顺序通常由下往上数, 可以是顺时针也可以是逆时针,这通常取决于我们从哪个方向看三角形。 通常,当mesh渲染时,"逆时针" 的面会被挡掉。 我们希望保证顺时针的面与法线的主向一致 */
int[] indices = new int[6];
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 0;
indices[4] = 2;
indices[5] = 3;
Mesh mesh = new Mesh();
mesh.vertices = vertices;
mesh.normals = normals;
mesh.uv = uv;
mesh.triangles = indices;
MeshFilter meshfilter = this.gameObject.GetComponent<MeshFilter>();
meshfilter.mesh = mesh;
}
}
程序结构说明:
creatQuad()函数实现所有功能,由Start()函数调用。
效果图:

一个细节知识备注:
顶点,三角形,法线,uv坐标, 绝对必要的部分只有顶点和三角形。
如果模型中不需要场景中的光照,那么就不需要法线。如果模型不需要贴材质,那么就不需要UV 。
