- Home /
Alter mesh UVs for Texture Atlas
I have a game with playing cards. My playing card model has 2 sub meshes, one for the front and one for the back of the card. I have my app working where when I deal different cards, I load a different texture onto the front of the card’s material. So now I am looking to optimize my code by combining all 52 card faces into a single Texture Atlas, so the face’s material would point to that. Then I was going to change the uvs for each card to display the correct card face. In this way I was hoping that I would reduce the draw calls.
To experiment, I tried getting the triangles for just the front submesh, then I tried to alter the uvs for just those triangles and put it back into the mesh. When looking at a single card, I thought I’d test it out by leaving the single texture and altering the uv’s to take the top left 1/4 of the card by lerping from to 0 - 0.5 for both x and y. But it does not seem to work that way. I get a extremely zoomed in upper right corner of the card when I do this.
When I spin the model around, the card back is not affected, so I think I am altering the correct uv’s…
MeshFilter filter = this.GetComponent<MeshFilter>();
if (filter != null) {
int[] frontFaceTris = filter.mesh.GetTriangles(1);
List<Vector2> uvs0 = new List<Vector2>();
filter.mesh.GetUVs(0, uvs0);
Vector2 uv = Vector2.zero;
float xout = 0;
float yout = 0;
foreach (int tri in frontFaceTris![alt text][1]) {
uv = uvs0[tri];
xout = Mathf.Lerp(0f, 0.5f, uv.x);
yout = Mathf.Lerp(0f, 0.5f, uv.y);
uvs0[tri] = new Vector2(xout, yout);
}
filter.mesh.SetUVs(0, uvs0);
}
Attached is a before and after image of my model. Can anyone help?
[1]: /storage/temp/66000-before-after-alter-uvs.jpg
Ok I figured out my problem. Since many of the vertices are shared between triangles, I was scaling the uv's for those verts multiple times which was causing distortion. To solve this I created an array of bools the size vertexCount. If I scale the uv for a vert, I set that vert's flag to true, so I would not scale it again, and I would check that flag before scaling a uv.