1. 程式人生 > >Unity3d 利用Mesh繪製幾何圖形實現

Unity3d 利用Mesh繪製幾何圖形實現

一、建立一個GameObject,並在上面掛兩個元件(MeshFilter、MeshRenderer)

二、新建個指令碼,並掛在剛才建立的GameObject上

    using UnityEngine;    using System.Collections;
         public class MeshImage : MonoBehaviour
{
         void Start()
    {
    MeshRectangle();
    }
// 建立一個矩形

    void MeshRectangle()
    {
    MeshFilter mFilter = gameObject.GetComponent();

    MeshRenderer mRen = gameObject.GetComponent();

//矩形的四個頂點座標

    Vector3[] vertices = new Vector3[4];
    vertices[0] = new Vector3(0, 0, 0);
    vertices[1] = new Vector3(500, 0, 0);
    vertices[2] = new Vector3(500, 500, 0);
    vertices[3] = new Vector3(0, 500, 0);

         //三角形頂點索引

    int[] triangles = new int[6]{0, 1, 2, 2, 3, 0};


         //每個頂點的法線    

Vector3[] normals = new Vector3[4];
    normals[0] = new Vector3(0, 0, -5);
    normals[1] = new Vector3(0, 0, -5);
    normals[2] = new Vector3(0, 0, -5);
    normals[3] = new Vector3(0, 0, -5);

         //UV貼圖座標

    Vector2[] uvs = new Vector2[4];
    uvs[0] = new Vector2(0, 0);
    uvs[1] = new Vector2(1, 0);

    uvs[2] = new Vector2(1, 1);
    uvs[3] = new Vector2(0, 1);         

//頂點顏

    Color32[] colors32 = new Color32[4];
    colors32[0] = new Color32(255, 0, 0, 255);
    colors32[1] = new Color32(255, 0, 0, 255);
    colors32[2] = new Color32(255, 0, 0, 255);
    colors32[3] = new Color32(255, 0, 0, 255);

    Mesh mesh = new Mesh();

    mesh.hideFlags = HideFlags.DontSave;
    mesh.vertices = vertices;
    mesh.triangles = triangles;
    mesh.colors32 = colors32;
    mesh.uv = uvs;
    mesh.normals = normals;
         mFilter.mesh = mesh;

    }
    }

物件層次結構
執行效果(PS: 自己通過調整相機位置從不同角度去觀察)