LWJGL Forum

Programming => Lightweight Java Gaming Library => Topic started by: ChaoticCactus on June 04, 2013, 20:50:15

Title: Texture Binding NullPointerException
Post by: ChaoticCactus on June 04, 2013, 20:50:15
Hello again!

So I'm trying to assign a texture to my sprites.  I have a GameObject class that utilizes the Sprite class.  Like so:

protected void init(float x, float y, Texture texture, float sizeX, float sizeY, int type) {
       this.x = x;
       this.y = y;
       this.type = type;
       this.spr = new Sprite(texture, sizeX, sizeY);
   }


And for my player class, which extends GameObject, I have this in the constructor:

public Player(float x, float y) {
       init(x, y, player /* Texture player */, SIZE_X, SIZE_Y, PLAYER_ID);

       try {
           player = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/Player.png"));
       } catch(IOException e) {
           e.printStackTrace();
       }
   }


and this is the rendering code for all of the GameObjects:

public void render() {
       texture.bind();

       glBegin(GL_QUADS);
           glVertex2f(0, 0);
           glVertex2f(0, sizeY);
           glVertex2f(sizeX, sizeY);
           glVertex2f(sizeX, 0);
       glEnd();
   }


Why am I getting a NullPointerException on texture.bind(); ?

EDIT:  I feel stupid now.  I moved the try block where I initialized the textures above the init part of the constructor.  But when I run it there textures don't appear. They're just different shades of grey.  Hmmm, anybody know how I can fix it?
Title: Re: Texture Binding NullPointerException
Post by: fiendfan1 on June 04, 2013, 23:17:10
In your render method, you need to tell opengl what texture coordinates to use for each vertex.

To do this you use GL11.glTexCoord2f(float x, float y).

The x and y values are between 0 and 1.
So glTexCoord2f(0, 0) would be the top left corner of the texture
glTexCoord2f(1, 1) would be the bottom right corner of the texture


So it would be something like this:

public void render() {
        texture.bind();

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

            glTexCoord2f(0, 1);
            glVertex2f(0, sizeY);

            glTexCoord2f(1, 1);
            glVertex2f(sizeX, sizeY);

            glTexCoord2f(1, 0);
            glVertex2f(sizeX, 0);
        glEnd();
}

Title: Re: Texture Binding NullPointerException
Post by: ChaoticCactus on June 04, 2013, 23:33:52
... I feel stupid now.

Well, thank you!  Problem solved!