- Home /
Save only visible part of mesh
I am trying to save only visible parts of my cloth mesh as obj file. So far I have the visible vertices and their corresponding vertex indices (triangles). But when I save my mesh, the visible part is removed and the rest is saved. i want to reach exactly the opposite but changing the if statement destroys the whole mesh. Please tell me where I go wrong.
void Update()
{
clothMesh = Instantiate(cloth.gameObject.GetComponent<MeshFilter>().sharedMesh);
Vector3[] vertices = clothMesh.vertices;
int[] triangles = clothMesh.triangles;
List<Vector3> visibleVertices = new List<Vector3>();
List<int> visibleTriIndecies = new List<int>();
//--find out the visible vertices
Vector3 visibleVertex = new Vector3();
for(int i=0; i < vertices.Length;i++)
{
visibleVertex = cam.WorldToScreenPoint(cloth.transform.TransformPoint( vertices[i]));
//---if vertex is visible
if(visibleVertex.x <= cam.pixelWidth && visibleVertex.x >= 0 && visibleVertex.y >= 0 && visibleVertex.y <= cam.pixelHeight)
{
visibleVertices.Add(vertices[i]);
}
}
//---find out the vertex index of visible vertices
for (int i = 0; i < triangles.Length; i+=3)
{
foreach(Vector3 vpoint in visibleVertices)
{
if(vpoint == vertices[triangles[i]])
{
visibleTriIndecies.Add(triangles[i]);
visibleTriIndecies.Add(triangles[i+1]);
visibleTriIndecies.Add(triangles[i+2]);
}
}
}
Mesh mesh = clothMesh;
int[] newtris = mesh.triangles;
for(int i = 0; i < visibleTriIndecies.Count; i+=3)
{
for(int j = 0; j < newtris.Length; j+=3)
{
if(newtris[j] == visibleTriIndecies[i] && newtris[j + 1] == visibleTriIndecies[i + 1] && newtris[j + 2] == visibleTriIndecies[i + 2])
{
newtris[j] = 0;
newtris[j + 1] = 0;
newtris[j + 2] = 0;
}
}
}
mesh.triangles = newtris;
Debug.Log("Vertex count: " + visibleVertices.Count);
SaveMeshAsObj(mesh);
Destroy(mesh);
}
Answer by DanaScully · Jul 04, 2017 at 06:52 AM
The answer was another for loop. May not be optimal but gives the result.
for(int i = 0; i < newtris.Length; i+=3) { if(newtris[i] == triangles[i] && newtris[i+1] == triangles[i+1] && newtris[i+2] == triangles[i+2]) { newtris[i] = 0; newtris[i + 1] = 0; newtris[i + 2] = 0; } else { newtris[i] = triangles[i]; newtris[i + 1] = triangles[i + 1]; newtris[i + 2] = triangles[i + 2]; } }
Your answer
Follow this Question
Related Questions
Generated Mesh Triangles not Being Made/Visible? 1 Answer
Extruding faces of a mold. Need to properly assign vertices to triangles 0 Answers
Null Reference Exception Assigning Vertices to Mesh 0 Answers
Why vertex positions appear (0.0, 0.0, 0.0) ? 1 Answer
Lighting up all triangles between two points in a mesh? 1 Answer