轉 mesh 生成模型

立方體

https://www.cnblogs.com/JLZT1223/category/911460.html   不錯的鏈接mesh

using UnityEngine;

[RequireComponent(typeof(MeshRenderer), typeof(MeshFilter))]
public class cube_mesh : MonoBehaviour
{
    public float Length = 5;              //長方體的長
    public float Width = 6;               //長方體的寬
    public float Heigth = 7;              //長方體的高
    private MeshFilter meshFilter;

    void Start()
    {
        meshFilter = GetComponent<MeshFilter>();
        meshFilter.mesh = CreateMesh(Length, Width, Heigth);
    }

    Mesh CreateMesh(float length, float width, float heigth)
    {

        //vertices(頂點、必須):
        int vertices_count = 4*6;                                 //頂點數(每個面4個點,六個面)
        Vector3[] vertices = new Vector3[vertices_count];
        vertices[0] = new Vector3(0, 0, 0);                     //前面的左下角的點
        vertices[1] = new Vector3(0, heigth, 0);                //前面的左上角的點
        vertices[2] = new Vector3(length, 0, 0);                //前面的右下角的點
        vertices[3] = new Vector3(length, heigth, 0);           //前面的右上角的點

        vertices[4] = new Vector3(length, 0, width);           //後面的右下角的點
        vertices[5] = new Vector3(length, heigth, width);      //後面的右上角的點
        vertices[6] = new Vector3(0, 0, width);                //後面的左下角的點
        vertices[7] = new Vector3(0, heigth, width);           //後面的左上角的點

        vertices[8] = vertices[6];                              //左
        vertices[9] = vertices[7];
        vertices[10] = vertices[0];
        vertices[11] = vertices[1];

        vertices[12] = vertices[2];                              //右
        vertices[13] = vertices[3];
        vertices[14] = vertices[4];
        vertices[15] = vertices[5];

        vertices[16] = vertices[1];                              //上
        vertices[17] = vertices[7];
        vertices[18] = vertices[3];
        vertices[19] = vertices[5];

        vertices[20] = vertices[2];                              //下
        vertices[21] = vertices[4];
        vertices[22] = vertices[0];
        vertices[23] = vertices[6];


        //triangles(索引三角形、必須):
        int 分割三角形數 = 6 * 2;
        int triangles_cout = 分割三角形數 * 3;                  //索引三角形的索引點個數
        int[] triangles = new int [triangles_cout];            //索引三角形數組
        for(int i=0,vi=0;i< triangles_cout;i+=6,vi+=4)
        {
            triangles[i] = vi;
            triangles[i+1] = vi+1;
            triangles[i+2] = vi+2;

            triangles[i+3] = vi+3;
            triangles[i+4] = vi+2;
            triangles[i+5] = vi+1;

        }

        //uv:
        //.........

        //負載屬性與mesh
        Mesh mesh = new Mesh();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        return mesh;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章