如何在Unity3d中按平面切割网格

时间:2016-01-18 14:04:35

标签: unity3d mesh

我想通过飞机切割网格。 试试这段代码,但只能获得切割网格的一部分。(http://prntscr.com/9rne81http://prntscr.com/9rned3)。

public void SliceIt()
{
    Vector3[] vertices = mesh.vertices;

    Transform clone = clone = ((Transform)Instantiate(transform, transform.position + new Vector3(0, 0.25f, 0), transform.rotation));

    Mesh meshSlice  = clone.GetComponent<MeshFilter>().sharedMesh;
    Vector3[] verticesSlice = meshSlice.vertices;

    List<Vector3> verticesSlice2 = new List<Vector3>();

    Mesh cutplanemesh  = cutplane.GetComponent<MeshFilter>().sharedMesh;
    Vector3[] cutplanevertices = cutplanemesh.vertices;

    p1 = cutplane.TransformPoint(cutplanevertices[40]);
    p2 = cutplane.TransformPoint(cutplanevertices[20]);
    p3 = cutplane.TransformPoint(cutplanevertices[0]);
    var myplane = new Plane(p1, p2, p3);

    for (var i = 0; i < vertices.Length; i++)
    {
        var tmpverts = transform.TransformPoint(vertices[i]); // original object vertices

        if (myplane.GetSide(tmpverts))
        {
            vertices[i] = transform.InverseTransformPoint(new Vector3(tmpverts.x, tmpverts.y - (myplane.GetDistanceToPoint(tmpverts)), tmpverts.z));

            verticesSlice[i] = transform.InverseTransformPoint(new Vector3(tmpverts.x, tmpverts.y, tmpverts.z));
            var v = transform.InverseTransformPoint(new Vector3(tmpverts.x, tmpverts.y, tmpverts.z));
            verticesSlice2.Add(v);
        }
        else
        {
            var v = transform.InverseTransformPoint(new Vector3(tmpverts.x, tmpverts.y - (myplane.GetDistanceToPoint(tmpverts)), tmpverts.z));
            verticesSlice2.Add(v);
        }
    }

    mesh.vertices = verticesSlice;
    mesh.RecalculateBounds();

    meshSlice.vertices = verticesSlice2.ToArray();
    meshSlice.RecalculateBounds();

}

我做了这个代码:http://unitycoder.com/blog/2011/08/09/fake-mesh-slicer-v3-0/#comments

我读到了这个:http://answers.unity3d.com/questions/450272/cutting-a-mesh-into-smaller-pieces.html 但我不知道分裂三角形如何属于平面的正负面。

1 个答案:

答案 0 :(得分:0)

您可以在资产商店中使用现有的资产: https://www.assetstore.unity3d.com/#!/content/59618

它不仅可以切割网格,还可以切割对撞机,进行一些优化并且可以实现。