3

I am trying to calculate the uv's for a mesh I generate in code. It's a very simple circle (2d)

enter image description here

and I want to texture it like follows

enter image description here

and using this code for the uvs

uvs[i] = new Vector2((verts[i].x+radius)/(radius), (verts[i].y+radius)/(2*radius));

and the center vertex is (0.5f,0.5f)

but I am getting a distorted image. (EDIT PHOTO after help from answer but still stretched)

enter image description here

could anyone help here? Thanks in advance

KMoore
  • 171
  • 1
  • 10

1 Answers1

4

How about this:

Lets assume that the coordinates of the center vertex are (centerX, centerY)

uvs[i] = new Vector2(0.5f +(verts[i].x-centerX)/(2*radius), 
                             0.5f + (verts[i].y-centerY)/(2*radius));
andrew_m
  • 121
  • 3
  • Thank you, i didnt put the center parts in because the vertices are in local space and the center coord is (0,0) but it helped a lot. I have edited the photo. There is still some stretching though – KMoore Aug 23 '14 at 20:36
  • It looks that vertical coordinates are fine, just horizontal are wrong. As I can remember, UVs u and v should be from range 0.0 - 1.0 Your recent image suggests that your u is more like from -0.5 to 1.5, are you sure you did not forget to divide by (2*radius)? (as in your original code the x-coord was divided just by radius) – andrew_m Aug 23 '14 at 20:51
  • How can we perform a similar procedure for an arbitrary planar shape? Assume a 2d polygon, except the distance of the vertices to the center of the polygon is not the same. – Aaron Azhari Oct 16 '14 at 04:57
  • @AramAzhari You just need to scale and translate vertex coordinates into range [0.0 - 1.0]. This way you will get texture coordinates. You need to calculate the WIDTH (max x delta) and HEIGHT (max y delta) of your polygon. You also need the coordinates of the center of your polygon: centerX and centerY. Then for each vertex (x,y) you calculate its texture coordinates (u,v) in this way: `u = 0.5f + (x - centerX)/WIDTH;` `v = 0.5f + (y - centerY)/HEIGHT;` So for vertices: (-2, 4) (6, 1) (4, 7) WIDTH=8, HEIGHT=6, centerX=2, centerY=4 Texture coords: (0.0, 0.5) (1.0, 0.0) (0.75, 1.0) – andrew_m Nov 06 '14 at 23:49
  • @andrew_m I tried and it doesn't give what I want. I tried to explain my problem better [here](http://stackoverflow.com/questions/26397115/calculating-uv-texture-coords-for-a-procedurally-generated-polygon) – Aaron Azhari Nov 07 '14 at 09:12