'How to cut a mesh by plane in Unity3d
I want to cut meshes by plane. try this code, but get only one of parts of cutting mesh.
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |