[texture UVs] How to get a box at a specific part of a texture?

So I’m trying to make a method that returns a per-vertex (4) array of sub-texture UVs from a texture, and a rectangle.
Mainly for spritesheets really.


//tex.source = BufferedImage loaded correctly
//x, y, y1, y2 = The rectangle dimensions
//This is my attempt at making this block, it doesn't work, I can confirm that. I just need some help
//figuring this whole sub-tex coord thing out.
public static Vector2f[] getSubTextureUV(Texture tex, int x, int y, int x1, int y1){
	Vector2f[] texUV = new Vector2f[4];
	if(tex == null) throw new NullPointerException("Texture is null");
	
	texUV[0] = new Vector2f(0,                       y/tex.source.getHeight());
	texUV[1] = new Vector2f(0,                       0);
	texUV[2] = new Vector2f(x1/tex.source.getWidth(), 0);
	texUV[3] = new Vector2f(x1/tex.source.getWidth(), y1/tex.source.getHeight());
	
	System.out.println(texUV[0].x + " " + texUV[0].y);
	System.out.println(texUV[1].x + " " + texUV[1].y);
	System.out.println(texUV[2].x + " " + texUV[2].y);
	System.out.println(texUV[3].x + " " + texUV[3].y);
	
	return texUV;
}

...

Vector2f[] myTextureUVs = getSubTextureUV(myTex, 16, 16, 32, 32); //Would take the texture at point 16,16, and the resolution of 16,16

Current output:

0.0 0.0
0.0 0.0
0.0 0.0
0.0 0.0

(Not that it matters ;))

well, you are dividing 2 ints, so the result will be an int. you need something like this:


texUV[0] = new Vector2f(0,                       (float)y/tex.source.getHeight());
texUV[1] = new Vector2f(0,                       0);
texUV[2] = new Vector2f((float)x1/tex.source.getWidth(), 0);
texUV[3] = new Vector2f((float)x1/tex.source.getWidth(), (float)y1/tex.source.getHeight());

   texUV[0] = new Vector2f(0,                       y/tex.source.getHeight());
   texUV[1] = new Vector2f(0,                       0);
   texUV[2] = new Vector2f(x1/tex.source.getWidth(), 0);
   texUV[3] = new Vector2f(x1/tex.source.getWidth(), y1/tex.source.getHeight());

should also probably be:

   
   float u0 = (float) x / tex.source.getWidth();
   float v0 = (float) y / tex.source.getHeight();
   float u1 = (float) x1 / tex.source.getWidth();
   float v1 = (float) y1 / tex.source.getHeight();
   texUV[0] = new Vector2f(u0, v0);
   texUV[1] = new Vector2f(u0, v1);
   texUV[2] = new Vector2f(u1, v1);
   texUV[3] = new Vector2f(u1, v0);

assuming you are trying to make a rectangle with one corner at (x,y) and the other at (x1,y1)

+1 Thanks! It works.

Its flipped because of how I’m drawing my triangles. Pretty easy to fix.

You guys are the best :wink: