Bootstrap

Unity 依据Polygon Collider 2D 绘制 mesh

参考文章:
mesh的简介
创建mesh
简单多边形三角化(暴力)(削耳朵)

偶尔需要依据多边形创建平面mesh,所以在网上浏览了很多资料,再修修补补才凑出一段代码。

    [ContextMenu("Create_Mesh_For_PolygonCollider2D")]
    void Create_Mesh_For_PolygonCollider2D()
    {
   

        PolygonCollider2D pc = GetComponent<PolygonCollider2D>();
        //获取多边形碰撞体的顶点
        Vector3[] v_vertices = new Vector3[pc.points.Length];
        for (int i = 0; i < pc.points.Length; i++)
        {
   
            v_vertices[i] = new Vector3(pc.points[i].x, pc.points[i].y, 0);
        }
        DoCreatPloygonMesh(v_vertices);
    }

    //*****  创建mesh
    void DoCreatPloygonMesh(Vector3[] s_Vertives)
    {
   

        //新建一个空物体进行进行绘制自定义多边形
        GameObject tPolygon = new GameObject("tPolygon");
        tPolygon.transform.parent = transform;
        //绘制所必须的两个组件
        tPolygon.AddComponent<MeshFilter>();
        tPolygon.AddComponent<MeshRenderer>();

        //新申请一个Mesh网格
        Mesh tMesh = new Mesh();

        //存储所有的顶点
        Vector3[] tVertices = s_Vertives;

        //存储画所有三角形的点排序
        List<int> tTriangles = Calculate_Triangles_CutEar_Method(tVertices)
;