简体   繁体   中英

How would I read a sprite sheet in LWJGL?

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.

eg:

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM