Unity dynamically builds Mesh to draw arbitrary polygons (radar effect)

Since many students did not make it, we hereby post a Demo project (version Unity2019.1.8f1)

CSDN download: https://download.csdn.net/download/linxinfa/11956009

In addition, I also uploaded the Demo project to GitHub, (Unity version: 2020.1.2f1c1) can be downloaded directly on GitHub: https://github.com/linxinfa/Unity-ArbitraryPolygonMesh

 


scenes to be used

Radar chart

principle

It is to dynamically new a Mesh, set the triangle and fixed-point data, and then assign it to the MeshFilter, and draw it through the MeshRenderer

step

1 Copy the script below the article to the project

2 Create an empty object in the scene, name it Mesh, and hang the PolygonDrawer component

3 Create N Spheres under the Mesh object

4 Create a shader, select the shader you need, for example, the following is Unlit/Color, and adjust the color to blue

5 Assign the shader to the PolygonDrawer component

6 Assign N Spheres to the PolygonDrawer component (note the placement of N Spheres, the script in this article only supports clockwise or counterclockwise order)

7 Run Unity, pay attention to running before you can see the dynamically constructed polygon Mesh effect

supplement

Some students in the comment area said there was a problem. I tried it with Unity5.x, Unity2017 and Unity2019, and they all can be displayed normally.

The effect is as follows

 

 

Code

MethodExtensionForUnity.cs

using UnityEngine;

//Unity的一些扩展方法
static public class MethodExtensionForUnity
{
    /// <summary>
    /// Gets or add a component. Usage example:
    /// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
    /// </summary>
    static public T GetOrAddComponent<T>(this Component child, bool set_enable = false) where T : Component
    {
        T result = child.GetComponent<T>();
        if (result == null)
        {
            result = child.gameObject.AddComponent<T>();
        }
        var bcomp = result as Behaviour;
        if (set_enable)
        {
            if (bcomp != null) bcomp.enabled = true;
        }
        return result;
    }

    static public T GetOrAddComponent<T>(this GameObject go) where T : Component
    {
        T result = go.transform.GetComponent<T>();
        if (result == null)
        {
            result = go.AddComponent<T>();
        }
        var bcomp = result as Behaviour;
        if (bcomp != null) bcomp.enabled = true;
        return result;
    }


    public static void walk(this GameObject o, System.Action<GameObject> f)
    {
        f(o);

        int numChildren = o.transform.childCount;

        for (int i = 0; i < numChildren; ++i)
        {
            walk(o.transform.GetChild(i).gameObject, f);
        }
    }


}


Triangulator.cs

using UnityEngine;
using System.Collections.Generic;
 
public class Triangulator
{
    private List<Vector2> m_points = new List<Vector2>();
 
    public Triangulator (Vector2[] points) {
        m_points = new List<Vector2>(points);
    }
 
    public int[] Triangulate() {
        List<int> indices = new List<int>();
 
        int n = m_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)
                return indices.ToArray();
 
            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;
            }
        }
 
        indices.Reverse();
        return indices.ToArray();
    }
 
    private float Area () {
        int n = m_points.Count;
        float A = 0.0f;
        for (int p = n - 1, q = 0; q < n; p = q++) {
            Vector2 pval = m_points[p];
            Vector2 qval = m_points[q];
            A += pval.x * qval.y - qval.x * pval.y;
        }
        return (A * 0.5f);
    }
 
    private bool Snip (int u, int v, int w, int n, int[] V) {
        int p;
        Vector2 A = m_points[V[u]];
        Vector2 B = m_points[V[v]];
        Vector2 C = m_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 = m_points[V[p]];
            if (InsideTriangle(A, B, C, P))
                return false;
        }
        return true;
    }
 
    private 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));
    }
}

PolygonDrawer.cs

using UnityEngine;

/// <summary>
/// 绘制多边形
/// TODO: 存在两点重合时绘制有问题
/// </summary>
public class PolygonDrawer : MonoBehaviour
{
    public Material material;
    public Transform[] vertices;
    private MeshRenderer mRenderer;
    private MeshFilter mFilter;

    void Start()
    {
        Draw();
    }

    void Update()
    {
        Draw();
    }

    [ContextMenu("Draw")]
    public void Draw()
    {
        Vector2[] vertices2D = new Vector2[vertices.Length];
        Vector3[] vertices3D = new Vector3[vertices.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            Vector3 vertice = vertices[i].localPosition;
            vertices2D[i] = new Vector2(vertice.x, vertice.y);
            vertices3D[i] = vertice;
        }

        Triangulator tr = new Triangulator(vertices2D);
        int[] triangles = tr.Triangulate();

        Mesh mesh = new Mesh();
        mesh.vertices = vertices3D;
        mesh.triangles = triangles;

        if (mRenderer == null)
        {
            mRenderer = gameObject.GetOrAddComponent<MeshRenderer>();
        }
        mRenderer.material = material;
        if (mFilter == null)
        {
            mFilter = gameObject.GetOrAddComponent<MeshFilter>();
        }
        mFilter.mesh = mesh;
    }
}

 

 

 

 

Guess you like

Origin blog.csdn.net/linxinfa/article/details/78816362