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?

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.