My program is taking in a texture and splitting the texture into randomly sized pieces that are made into 2D meshes (like a puzzle). The textures I use often contain large sections of transparency so I often end up with some puzzle pieces (meshes) where all the pixels are transparent. How do I identify if the texture mapped to the meshes UV coordinates are transparent?
I’ve read here: [Get average color of the texture assigned to a mesh triangle][1]
But I don’t understand this part in the answer: “You’d code a likewise-not-too-difficult function to examine each pixel within the triangle based on its 3 UV coordinates”. I think I just need a nudge in the right direction on how to get the pixels of a mesh under a triangle.
Here is my code:
private void CreatePuzzlePieces(List<VoronoiCell2> cells, List<Vector2> imageBox)
{
for (int i = 0; i < cells.Count; i++)
{
VoronoiCell2 cell = cells*;*
List vertices = new List();
// Get the vertices of the mesh (puzzle piece)
for (int j = 0; j < cell.edges.Count; j++)
{
Vector3 p3 = cell.edges[j].p1.ToVector3();
Vector3 p2 = cell.edges[j].p2.ToVector3();
vertices.Add(p2);
vertices.Add(p3);
}
Vector3[] meshVertices = new Vector3[vertices.Count];
Vector2[] uv = new Vector2[vertices.Count];
int triangleCount = (vertices.Count - 2) * 3;
int[] triangles = new int[triangleCount];
// Scale the mesh to fit within the imagebox
for (int j = 0; j < vertices.Count; j++)
{
meshVertices[j] = new Vector3((vertices[j].x - imageBox[0].x) / (imageBox[1].x - imageBox[0].x),
(vertices[j].y - imageBox[0].y) / (imageBox[1].y - imageBox[0].y));
uv[j] = meshVertices[j];
}
// Build triangles
// This will only work for polygons without any concave features and it
// uses a more efficent approach (fewer triangles) than DisplayVoronoiCells()
// but may not work for polygons with 9 or more sides but that is unlikely to
// occur with Voronoi algorithm
int triPos = 0;
int curr = 0;
int loop = 1;
for (int j = 0; j < triangleCount; j++)
{
if (triPos == 3)
{
curr -= 1 * loop;
triangles[j] = curr;
triPos = 0;
}
else
{
if (curr >= vertices.Count)
{
curr = 0;
loop++;
}
triangles[j] = curr;
}
curr += 1 * loop;
triPos++;
}
Mesh mesh = new Mesh();
mesh.vertices = meshVertices;
mesh.uv = uv;
mesh.triangles = triangles;
GameObject goPiece = new GameObject(“PuzzlePiece”, typeof(MeshFilter), typeof(MeshRenderer));
goPiece.transform.position = puzzleBox.transform.position;
MeshRenderer rendererPiece = goPiece.GetComponent();
goPiece.GetComponent().mesh = mesh;
rendererPiece.material = image;
// ------------------------------------------------------------------------
// Here is where I want to check the percent of mesh (pixels) that is fully transparent:
if ( mesh contains > 99% transparent pixels) do something
// ------------------------------------------------------------------------
}
}
[1]: Get average color of the texture assigned to a mesh triangle - Questions & Answers - Unity Discussions