How would I read a sprite sheet in LWJGL?

2019-04-16 07:31发布

问题:

I currently use LWJGL Textures to draw images on the screen. I would like to read Textures* from a sprite sheet. I am using slick's TextureLoader class to load the textures.

I draw an LWJGL Shape and bind a Texture onto it.

e.g:

Me drawing an image:

    Texture texture = ResourceManager.loadTexture("Images/Tests/test.png");

    GL11.glBegin(GL11.GL_QUADS);
    {
      GL11.glTexCoord2f(0, 0);
      GL11.glVertex2f(0, 0);
      GL11.glTexCoord2f(0, texture.getHeight());
      GL11.glVertex2f(0, height);
      GL11.glTexCoord2f(texture.getWidth(), texture.getHeight());
      GL11.glVertex2f(width,height);
      GL11.glTexCoord2f(texture.getWidth(), 0);
      GL11.glVertex2f(width,0);
    }
    GL11.glEnd();

I think there is a way by when calling glTexCoord2f, I could give it a sprite offset and load the sprite sheet in the texture instead,

for example one call would be like this:

      GL11.glTexCoord2f(0+spriteXOffset, texture.getHeight()-spriteYOffset);

But I would really like to know if there is a simpler way, maybe extracting Textures from a single texture for example like they do in here:

Reading images from a sprite sheet Java

Just instead of BufferedImage, Texture object.

Thank you for the help!

回答1:

Texture coordinates for GL_TEXTURE_2D, used internally by the Slick texture loader, require normalized texture coordinates. That is, the coordinates range from 0.0 to 1.0. So (0,0) is the top-left corner of the texture, and (1,1) is the bottom-right corner. Assuming that you have your sprite coordinates in pixel coordinates at hand, you then have to divide the x coordinate by the texture width and the y coordinate by the texture height, resulting in normalized texture coordinates. You would then supply these coordinates to OpenGL using glTexCoord.

glTexCoord2f(spriteX / textureWidth, spriteY / textureHeight);
glVertex2f(coordinateX, coordinateY);
glTexCoord2f(spriteX+spriteWidth / textureWidth, spriteY / textureHeight);
glVertex2f(coordinateX2, coordinateY);
// Et cetera

There is, however, also an easier way of doing this. Take a look at this video (I created it), to see how you can use the pixel coordinates for textures instead of normalized ones.