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*));*
//—if vertex is visible
if(visibleVertex.x <= cam.pixelWidth && visibleVertex.x >= 0 && visibleVertex.y >= 0 && visibleVertex.y <= cam.pixelHeight)
{
visibleVertices.Add(vertices*);*
}
}
//—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*])*
{
visibleTriIndecies.Add(triangles*);*
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 && 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);
}