Spritesheets by dividing texture coordinates?

So I’m making a 2D engine with LWJGL and wanted a spritesheet class, and thought that the best way to do it in OpenGL, would be to load the entire spritesheet, then divide the tex coords according to which sprite I want to access. I came up with this:

for(int x = 0; x < sheet.getWidth(); x++){
for(int y = 0; y < sheet.getHeight(); y++){
textures[x][y] = new Texture(path, false, new Vector2f[]{
//init tex coords
new Vector2f(x/spriteWidth, y/spriteHeight), //bottom left
new Vector2f((x+1)/spriteWidth, y/spriteHeight), //top left
new Vector2f((x+1)/spriteWidth, (y+1)/spriteHeight), //top right
new Vector2f(x/spriteWidth, (y+1)/spriteHeight) //bottom right
});
}
}

It turns out that way of dividing the tex coords doesn’t work too well xD. How should I go about doing it?

My first guess is that you are using integers instead of floats.
When you divide an int with another int it will floor the result…

E.g.
5 / 2 = 2

5f / 2f = 2,5f

Hope that helps :slight_smile:

Instead of this

(x+1)/spriteWidth

should be this:

(x+spriteWidth)/spriteWidth

lets say you have a texture with 16 sprites (4 x 4)
this means you have to do something like this (xindex and yindex ranging from 0 to 3):

float size = 1f / 4f;
new Vector2f(size * xindex, size * yindex), //bottom left
new Vector2f(size * (xindex+1), size * yindex), //top left
new Vector2f(size * (xindex+1), size * (yindex+1)), //top right
new Vector2f(size * xindex, size * (yindex+1)) //bottom right

I feel like I’m getting closer guys. Changing some of the variables to floats definitely helped. When I tried this:

float size = 1/width;
new Vector2f(size * x, size * y), //bottom left
new Vector2f(size * (x+1), size * y), //top left
new Vector2f(size * (x+1), size * (y+1)), //top right
new Vector2f(size * x, size * (y+1)) //bottom right

And then rendered the sprite from index (3,3), the texture was distorted, and when I tried this:

new Vector2f(x/spriteWidth, y/spriteHeight),
new Vector2f((x+spriteWidth)/spriteWidth, y/spriteHeight),
new Vector2f((x+spriteWidth)/spriteWidth, (y+spriteHeight)/spriteHeight),
new Vector2f(x/spriteWidth, (y+spriteHeight)/spriteHeight)

The texture was still distorted… I would’ve thought that at least 1 of these methods would work…

Any more ideas?

what value has width?

Sorry guys, I fixed it. The big noob inside me thought that the texture coordinate call goes before the vertex call. Also I screwed up the order of the texture coordinates, and one of Slick-Utils parameters. In the end it was RobinB’s solution that ended up working. Thanks to all of you!