Search code examples
c#unity-game-enginevertexuv-mapping

With a UV layout, how can I best modify this function to access any part of my texture?


I've been trying to reduce the code used in my voxel / planar terrain generator, and wrote this function in order to call every time I need to add a new set of UV's - representing four vertex in a texture map:

List<Vector2> _UVs(List<Vector2> UV, int x = 0, int y = 0)
{
    List<Vector2> UVReturn = new List<Vector2>();
    UVReturn = UV;

    UVReturn.Add(new Vector2 (0f, 0f) * x);
    UVReturn.Add(new Vector2 (0.125f, 0) * y);
    UVReturn.Add(new Vector2 (0.125f, 1)* y);
    UVReturn.Add(new Vector2 (0f, 1f) * x); 

    return UVReturn;
}

However, I can't seem to identify the exact spots to write in the modifiers, they seem to throw things off every time. I currently have a single row of 128x textures in a 1024 file. The UV layout for the moment seems exact, except for the multiplication. Remove that and it shows the first texture, perfectly. What ways can this be improved on? My goal would be to get it to where it could be used for any four vertex plane.


Solution

  • You can't just multiply it like that, that's something completely different.

    UVReturn.Add(new Vector2 (x * 0.125f, 0f));
    UVReturn.Add(new Vector2 ((x + 1) * 0.125f, 0));
    UVReturn.Add(new Vector2 ((x + 1) * 0.125f, 1));
    UVReturn.Add(new Vector2 (x * 0.125f, 1f));
    

    You need to offset the UV coordinates - that means you have to add x * widthOfOne to the x coordinates, and y * heightOfOne to the y coordinates. My sample only shows the x-offset, but you can easily expand it to allow y-offsets as well.