Unity 網格 繪制


網格繪制主要用是對Mesh進行操作,通過對vertex和triangles進行操作生成對應的面片;

這里首先得用到一個類:Triangulator(根據vertex生成triangles數組)

using UnityEngine;
using System.Collections.Generic;

public class Triangulator
{
    private static List<Vector2> points;
    private static Vector3 cameraPosition;

    public static Vector2[] ToVector2(Vector3[] m_points)
    {
        Vector2[] vertices2d = new Vector2[m_points.Length];
        for (int i = 0; i < m_points.Length; i++)
        {
            Vector3 pos = m_points[i];
            vertices2d[i] = new Vector2(pos.x, pos.z);
        }
        return vertices2d;
    }

    public static int[] Triangulate(Vector2[] m_points, Vector3 m_cameraPosition)
    {
        points = new List<Vector2>(m_points);
        cameraPosition = m_cameraPosition;

        List<int> indices = new List<int>();

        int n = points.Count;
        if (n < 3)
            return indices.ToArray();

        int[] V = new int[n];
        if (Area() > 0)
        {
            for (int v = 0; v < n; v++)
                V[v] = v;
        }
        else
        {
            for (int v = 0; v < n; v++)
                V[v] = (n - 1) - v;
        }

        int nv = n;
        int count = 2 * nv;
        for (int m = 0, v = nv - 1; nv > 2;)
        {
            if ((count--) <= 0)
                break;

            int u = v;
            if (nv <= u)
                u = 0;
            v = u + 1;
            if (nv <= v)
                v = 0;
            int w = v + 1;
            if (nv <= w)
                w = 0;

            if (Snip(u, v, w, nv, V))
            {
                int a, b, c, s, t;
                a = V[u];
                b = V[v];
                c = V[w];
                indices.Add(a);
                indices.Add(b);
                indices.Add(c);
                m++;
                for (s = v, t = v + 1; t < nv; s++, t++)
                    V[s] = V[t];
                nv--;
                count = 2 * nv;
            }
        }

        bool reversFlag = true;
        int i0 = indices[0];
        int i1 = indices[1];
        int i2 = indices[2];
        Vector3 pos0 = new Vector3(points[i0].x, 0f, points[i0].y);
        Vector3 pos1 = new Vector3(points[i1].x, 0f, points[i1].y);
        Vector3 pos2 = new Vector3(points[i2].x, 0f, points[i2].y);
        Vector3 v1 = pos1 - pos0;
        Vector3 v2 = pos2 - pos1;
        Vector3 crossVec = Vector3.Cross(v1, v2);
        if (Vector3.Dot(cameraPosition, crossVec) > 0)
        {
            reversFlag = false;
        }
        if (reversFlag)
        {
            indices.Reverse();
        }

        return indices.ToArray();
    }

    private static float Area()
    {
        int n = points.Count;
        float A = 0.0f;
        for (int p = n - 1, q = 0; q < n; p = q++)
        {
            Vector2 pval = points[p];
            Vector2 qval = points[q];
            A += pval.x * qval.y - qval.x * pval.y;
        }
        return (A * 0.5f);
    }

    private static bool Snip(int u, int v, int w, int n, int[] V)
    {
        int p;
        Vector2 A = points[V[u]];
        Vector2 B = points[V[v]];
        Vector2 C = points[V[w]];
        if (Mathf.Epsilon > (((B.x - A.x) * (C.y - A.y)) - ((B.y - A.y) * (C.x - A.x))))
            return false;
        for (p = 0; p < n; p++)
        {
            if ((p == u) || (p == v) || (p == w))
                continue;
            Vector2 P = points[V[p]];
            if (InsideTriangle(A, B, C, P))
                return false;
        }
        return true;
    }

    private static bool InsideTriangle(Vector2 A, Vector2 B, Vector2 C, Vector2 P)
    {
        float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
        float cCROSSap, bCROSScp, aCROSSbp;

        ax = C.x - B.x; ay = C.y - B.y;
        bx = A.x - C.x; by = A.y - C.y;
        cx = B.x - A.x; cy = B.y - A.y;
        apx = P.x - A.x; apy = P.y - A.y;
        bpx = P.x - B.x; bpy = P.y - B.y;
        cpx = P.x - C.x; cpy = P.y - C.y;

        aCROSSbp = ax * bpy - ay * bpx;
        cCROSSap = cx * apy - cy * apx;
        bCROSScp = bx * cpy - by * cpx;

        return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f));
    }
}
Triangulator.cs

然后我們創建一個腳本:DrawMesh.cs

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

public class DrawMesh : MonoBehaviour
{
    #region 公共變量
    /// <summary>
    /// 繪制模式,間斷、連續
    /// </summary>
    public enum DrawMeshModel { Intermittently, Continuously };

    /// <summary>
    /// 線段材質、網格材質
    /// </summary>
    public Material lineMat, meshMat;

    /// <summary>
    /// 繪制模式
    /// </summary>
    public DrawMeshModel drawModel = DrawMeshModel.Intermittently;

    public float lineWidth = 0.5f;//線段寬度
    public float meshAlpha = 0.2f;//網格透明度
    #endregion

    #region 私有變量
    Vector3[] points = new Vector3[0];

    LineRenderer lineTemp;
    GameObject lineObject;

    MeshFilter meshFilter;
    GameObject meshObject;
    Mesh mesh;//網格

    Ray ray;
    RaycastHit hit;

    /// <summary>
    /// 記錄上一點位置
    /// </summary>
    Vector3 last = Vector3.zero;
    #endregion

    void Start()
    {
        lineObject = new GameObject("LineGameObject");
        lineTemp = lineObject.AddComponent<LineRenderer>();
        lineTemp.SetWidth(lineWidth, lineWidth);
        lineTemp.material = lineMat;

        meshObject = new GameObject("MeshGameObject");
        meshFilter = meshObject.AddComponent<MeshFilter>();
        meshObject.AddComponent<MeshRenderer>();
        meshObject.GetComponent<Renderer>().material = meshMat;
        Color tempColor = meshMat.color;
        tempColor.a = meshAlpha;
        meshMat.color = tempColor;
        mesh = new Mesh();

        lineObject.SetActive(false);
    }

    void Update()
    {
        if (Input.GetMouseButton(2) && drawModel == DrawMeshModel.Continuously 
        || Input.GetMouseButtonDown(2) && drawModel == DrawMeshModel.Intermittently) { if (!lineObject.activeInHierarchy) lineObject.SetActive(true); ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { if (drawModel == DrawMeshModel.Continuously) { if (last == Vector3.zero) { last = hit.point; return; } else if (Vector3.Distance(last, hit.point) < 1f) { return; } last = hit.point; } Array.Resize(ref points, points.Length + 1); points[points.Length - 1] = hit.point + new Vector3(0, 0.25f, 0); lineTemp.SetVertexCount(points.Length); lineTemp.SetPosition(points.Length - 1, points[points.Length - 1]); if (points.Length > 2) { mesh.vertices = points; mesh.triangles = Triangulator.Triangulate(Triangulator.ToVector2(points), Camera.main.transform.position); meshFilter.mesh = mesh; } } } } }

將DrawMesh腳本放置到物體上,給LineRenderer和Mesh賦上材質,這里我創建了一個枚舉:DrawMeshModel;

通過選擇Draw Model為Intermittently進行點擊繪圖,選擇Continuously進行連續繪圖;

設置線段寬度Line Width,網格透明度Mesh Alpha;

最后通過鼠標在Collider上繪制Mesh形狀。

最終效果1:

最終效果2:

 

截圖和GIF並非同一次畫的,錄的視頻沒上傳成功,只好轉成了gif,另外又截了圖。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM