5

I want to cut meshes by plane. try this code, but get only one of parts of cutting mesh.

Screenshot 1

Screenshot 2

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();

}

I got this code from here.

I also read this question, but I couldn't figure how to split triangles which belong to positive and negative sides of plane.

Bikram Kumar
  • 393
  • 1
  • 4
  • 15
Knaus Irina
  • 789
  • 5
  • 15
  • 35

1 Answers1

-3

You can use already existing assets on asset store: https://www.assetstore.unity3d.com/#!/content/59618

It is not only cut a mesh, it also cut colliders, do some optimizations and it is extandable.

Stas BZ
  • 1,184
  • 1
  • 17
  • 36
  • 2
    This is the correct answer. It's inconceivable you'd start writing mesh-cutting software from scratch. (Note that "unity" has nothing to do with the issue.) It would be very much like asking "I'm trying to use an SQL database in Unity, and, I need to know how to engineer an SQL database from scratch." It just ........ doesn't make much sense. – Fattie Mar 29 '19 at 13:49
  • Ideally you shouldn't suggest things that the OP has to pay for. You don't know their budget, free options are ideal. – Sophie Coyne Mar 10 '20 at 16:47