ERROR Drawing Texture in LWJGL

I have been using the code in the LWJGL wiki Space Invaders example to load the textures from BufferedImage. Here’s the code I have found to draw the texture.


public void drawTexture(Texture tex, float x, float y, float width, float height)
{
    glPushMatrix();
    tex.bind();

    glTranslatef(x, y, 0);

    glBegin(GL_QUADS);
    {
        glTexCoord2f(0, 0);
        glVertex2f(0, 0);

        glTexCoord2f(0, tex.getHeight());
        glVertex2f(0, height);

        glTexCoord2f(tex.getWidth(), tex.getHeight());
        glVertex2f(width, height);

        glTexCoord2f(tex.getWidth(), 0);
        glVertex2f(width, 0);
    }
    glEnd();

    glPopMatrix();
}

And I’m calling this to load the Texture.


TextureLoader texLoader = new TextureLoader();
Texture tex = texLoader.getTexture("resources/testTex.png");
drawTexture(tex, 0, 0, 100, 100);

This is the output.

And this is the original image.

The texture isn’t being drawn perfectly and it is even going to the top right corner.

How can I fix it?

Texture coordinates range from 0-1.

Make sure that tex.getWidth/getHeight() returns a value between 0 and 1.

As a side note, use GL_TRIANGLES. GL_QUADS is BAD.

It is exactly 1.0 but I don’t understand. Can you explain what it means? And how to use [icode]GL_TRIANGLES[/icode] in 2d mode?

Probably due to your orthographic matrix or texture coordinates, as Heroes said. Also; if you are using a non-power-of-two texture and full texture coordinates (i.e. 1.0) then it might lead to the texture being rendered incorrectly. To fix; use correct texture coordinates, a non-power-of-two texture, or a better texture loader (SlickUtil is outdated).

Hate to say it, but the Space Invaders tutorial is pretty old. It uses “immediate mode” (glBegin/glEnd) which is deprecated, and teaches some poor practices. IMHO if you want to learn OpenGL, you should work with the programmable pipeline. There is more info here:

Specifically it would be helpful to learn about GL initialization, textures, and texture coordinates in OpenGL:


Using a library like lwjgl-basics would make sprite rendering a lot more efficient and a lot easier:

spriteBatch.begin();

spriteBatch.draw(myTex, x, y);
spriteBatch.draw(myTexSprite, x2, y2, width, height);

spriteBatch.end(); //push data to GL

LibGDX is an even more powerful library that I can’t recommend highly enough. :slight_smile:

Thanks. Enabling the [icode]GL_BLEND[/icode] made transparency work with this code.


glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

And after searching for “opengl 2d mode” found this call to [icode]glOrtho[/icode] and it just displayed on the top left corner.


glOrtho(0, Global.WIDTH, Global.HEIGHT, 0, -1, 1);