- Home /
How should I convert Vector2 Coordinates to UV Coordinates?
I created a function to slice texture atlases as long as each texture is the same size (Think like Minecraft). This function returns the upper-right hand corner of each texture on the atlas in a Vector2 coordinate. I can use this to figure out the 3 other points I need to texture a quad.
Here's my question. How do I convert these points on the image to UV coordinates? Should I be going about this a different way?
Answer by Dave-Carlile · Jul 07, 2015 at 01:22 AM
Texture coordinates range between 0 and 1. In the horizontal or u
direction 0 is on the left and 1 is on the right. In the vertical or v
direction 0 is on the bottom and 1 is on the top. Another way to look at this is the lower left corner is at uv=0,0
and the upper right corner is at uv=1,1
.
So you need to figure out where in texture space your sprite texture is within your atlas. You can figure this out given the texture atlas size and the pixel coordinates of your sprite corners.
To map between the pixels and textures you just divide the pixel position by the width of the texture. This basically gives you a percentage. For example, if your atlas is 256 wide and the corner pixel is at x=128
, you calculate the u texture coordinate like this:
u = 128 / 256
Doing the math gives you 0.5, which makes sense because the pixel at x=128
lies directly in the center of the atlas, and 0.5 is directly in the center between 0 and 1.
Do the same math with the y pixel coordinate and the texture atlas height.
All that said, Unity already has import functionality that can split the sprites for you and generate sprite objects without you doing all the work. Of course, if you're doing a Minecraft-like project and want moddable textures that doesn't work so well.
In that case you might look at Texture2D.PackTextures.
Oh my god I'm so angry with myself. I thought of this yesterday but I convinced myself it wouldn't work before I even tried it. Thanks man!
Your answer
Follow this Question
Related Questions
How do I convert a Vector2 from a UV coordinate to an absolute pixel position? 1 Answer
Mesh breaks apart when using vertex displacement with shadergraph. 3 Answers
How to set up UV for lightmaps for generated meshes? 4 Answers
texturing a procedurally created mesh 0 Answers
Same material renders differently on a mesh generated from script and normal cubes. 1 Answer