Search code examples
opengltextureslwjglanimated

LWJGL Animated Texture by coordinates is off


I'm trying to animate a texture in LWJGL using texture coordinates by dividing 1.0f by the number of frames (glTexCoords range from 0-1), which returns the interval of frames in the image like this:

    float f = 1.0f / mat.getFrames();
    GL11.glBegin(7);
    GL11.glTexCoord2f(0.0F, f*curFrame);
    GL11.glVertex2d(rX, rY);
    GL11.glTexCoord2f(1.0F, f*curFrame);
    GL11.glVertex2d(rX + this.size, rY);
    GL11.glTexCoord2f(1.0F, (f*curFrame)+f);
    GL11.glVertex2d(rX + this.size, rY + this.size);
    GL11.glTexCoord2f(0.0F, (f*curFrame)+f);
    GL11.glVertex2d(rX, rY + this.size);
    GL11.glEnd();   

Note this is mat.getFrames():

public int getFrames(){
return numOfFrames;
}

But when i use 1.0f/10(the image is 64x640) it does this: My problem But if I use 16 as the number of frames this happens:Another problem It seems to add some black frames. I don't see what's wrong here it loads the texture, divides 1 by the number of frames then it uses the current frame number * the number it divided for y1, then it uses y1+ the divided number for y2, witch, should theoretically work, but it doesn't.


Solution

  • It looks very much like your texture is not the size you think it is. You are probably using an image/texture loading library that pads sizes to powers of 2 during import.

    This means that the loaded image has a size of 64x1024, where 64x640 contain your original image (10 frames of 64x64 each), and the remaining 64x384 are black. This explains all of the symptoms:

    • When you draw 1/10 of the image, you see more than a frame. Since 1/10 of 1024 is 102.4, but the frame height is 64, you're drawing 102.4 / 64 = 1.6 frames.
    • When you pretend to have 16 frames, you get full frames, but get black frames. Since 1/16 of 1024 is 64, this matches your actual frame height. But only 10 of the 16 frames are valid. The remaining 6 show parts of the black padding.

    To fix this, you have a few options:

    • Check if the image/texture loading library has an option to prevent rounding up to powers of 2. Use it if there is.
    • Use a different library that does not have these archaic restrictions.
    • Actually use 1/16 as the multiplier for the texture coordinates, but draw only the number of frames (10) you actually have.