1. 程式人生 > >修改模型的網格資料(自定義Mesh)

修改模型的網格資料(自定義Mesh)

內容會持續更新,有錯誤的地方歡迎指正,謝謝!

有時,需要自定義mesh來繪製模型或圖形,可以程式碼控制,也可以shader控制,這裡介紹程式碼控制的方法:

何為Mesh

Mesh是模型的網格,一個3D模型的表面是由多個彼此相連的三角面構成。三維空間中,構成這些三角面的點以及三角形的邊的集合就是Mesh。

當頂點數超過3時,連線點順序不同,就可繪製出不同形狀的圖,所以必須要能控制連線點的順序。陣列mesh.triangles就是用來記錄連線三角形的順序的。由於每繪製一個三角形需要知道其三個頂點的順序,那麼繪製n個三角形就需要知道3*n個點的順序。即陣列mesh.triangles的長度是3的倍數。
e.g.繪製五邊形的mesh:mesh.triangles = new int[9]{1,2,3,1,3,4,1,4,5}


這裡寫圖片描述

基礎練習——>獲取模型的所有頂點座標

using UnityEngine;  
using System.Collections;  
public class GetVertex : MonoBehaviour 
{  
    void Start ()   
    {  
        Mesh mesh = GetComponent<MeshFilter>().mesh;  
        Vector3[] vertices = mesh.vertices;  
        foreach(Vector3 vertex in vertices)  
        {  
            Debug.Log(vertex);  
        }  
    }  
}  

進階練習——>自定義mesh

unity裡面一個物體要渲染出來 需要兩個元件 一個是MeshFilter 一個是MeshRender

using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Grid : MonoBehaviour 
{
	public int xSize, ySize;
	private Mesh mesh;
	private Vector3[] vertices;
    public Vector3 CustomNormal;
    public Vector4 CustomTangent;

    private void Awake () 
    {
		Generate();
	}

	private void Generate () 
	{
		GetComponent<MeshFilter>().mesh = mesh = new Mesh();
		mesh.name = "Procedural Grid";

		vertices = new Vector3[(xSize + 1) * (ySize + 1)];
		Vector2[] uv = new Vector2[vertices.Length];
		Vector4[] tangents = new Vector4[vertices.Length];
        Vector3[] normals = new Vector3[vertices.Length];
        Color[] colors = new Color[vertices.Length];


        for (int i = 0, y = 0; y <= ySize; y++) 
        {
			for (int x = 0; x <= xSize; x++, i++) 
			{
				vertices[i] = new Vector3(x, y);
				uv[i] = new Vector2((float)x / xSize, (float)y / ySize);
				tangents[i] = CustomTangent;
                normals[i] = CustomNormal;
                colors[i] = Color.white;
            }
		}
		mesh.vertices = vertices;
		mesh.uv = uv;
		mesh.tangents = tangents;
        mesh.normals = normals;
        mesh.colors = colors;

        int[] triangles = new int[xSize * ySize * 6];
		for (int ti = 0, vi = 0, y = 0; y < ySize; y++, vi++) 
		{
			for (int x = 0; x < xSize; x++, ti += 6, vi++) 
			{
				triangles[ti] = vi;
				triangles[ti + 3] = triangles[ti + 2] = vi + 1;
				triangles[ti + 4] = triangles[ti + 1] = vi + xSize + 1;
				triangles[ti + 5] = vi + xSize + 2;
			}
		}
		mesh.triangles = triangles;
	}
}