How to calculate UVs of a flat poligon mesh

2.9k views Asked by At

My game generates a flat surface (the floor of a building). It's a flat poligon mesh as shown in the picture:

enter image description here

The poligon is generated procedurally and will be different each time.

I need to map UV coordinates so that a standard square texture of, say,a floor made of bricks, is properly displayed.

What is the best way to assing the correct UV coordinates to each vertex?

1

There are 1 answers

1
Lincoln Cheng On BEST ANSWER

With an irregular shape, you might want to "paste" a texture across the mesh(imagine pasting a rectangular sticker across your mesh and cutting away those that fall outside your mesh shape).

For that type of mapping, you might want to use Mesh.bounds, which gives you the bounding box of your mesh in local coordinates, which is the area you are going to "paste" your texture over.

Mesh mesh = GetComponent<MeshFilter>();
Bounds bounds = mesh.bounds;

Get the vertices of your mesh:

Vector3[] vertices = mesh.vertices;

Now do the mapping:

Vector2[] uvs = new Vector2[vertices.Length];
for(int i = 0; i < vertices.Length; i++)
{
  uvs[i] = new Vector2(vertices[i].x / bounds.size.x, vertices[i].z / bounds.size.z);
}
mesh.uv = uvs;