"Convert" mesh to another programmatically

I need to somehow convert my mesh to another by adding or subtracting triangles and vertices and changing their position.

My goal is to transform my "monster" (that is, the single mesh) into a human (that is, the single mesh) smoothly inside Unity. Something similar to the "Crumple Modifier" which you can find in this project here

Sorry for my English, I'm not English English and thanks in advance.

+3


source to share


1 answer


Dynamic meshing:

MeshFilter meshFilter = GetComponent();
Mesh mesh = meshFilter.sharedMesh;

if (mesh == null){
    meshFilter.mesh = new Mesh();
    mesh = meshFilter.sharedMesh;
}

Vector3 p0 = new Vector3(0,0,0);
Vector3 p1 = new Vector3(1,0,0);
Vector3 p2 = new Vector3(0,1,0);
Vector3 p3 = new Vector3(0,0,1);

// clear mesh of current data
mesh.Clear();

// set vertices
mesh.vertices = new Vector3[]{p0,p1,p2,p3};

// set 
mesh.triangles = new int[]{
    0,1,2,
    0,2,3,
    2,1,3,
    0,3,1
};
mesh.RecalculateNormals();
mesh.RecalculateBounds();
mesh.Optimize();

      

Modifying existing vertices (will work similarly for faces):



// mesh.vertices returns a copy
Vector3[] vert_copy = mesh.vertices;
vert_copy[0] = new Vector3(10,11,12);
vert_copy[1] = new Vector3(13,14,15);

// reassign new vertices to mesh
mesh.vertices = vert_copy;

mesh.RecalculateNormals();
mesh.RecalculateBounds();
mesh.Optimize();

      

These calls get expensive when you recalculate normals and boundaries. If your mesh does not physically interact with other meshes when "transforming", you can defer RecalculateBounds () until after the "transform" is complete. Likewise, if you are only expecting small transformations per frame for your grid, you can limit RecalculateNormals () to every other frame, or every 300ms .

+2


source







All Articles