Search code examples
javaopengl2dlwjgl

How is glReadPixels work in OpenGL/LWJGL?


I'm trying to make a 2d collision detection system for my game in java/LWJGL/OpenGL.

My problem is the glReadPixels() acting strange and I don't know what am I doing wrong.

The problem is usually it gives back the perfect rgba code of the pixel, but somthimes it gives back negative numbers or colors that aren't on my screen. (For alpha I always get -1)

What can cause this problem?

My code:

    int size = 10;

    ByteBuffer pixels = BufferUtils.createByteBuffer(width * height * 4);

    glReadPixels(100, 500, size, size, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

I'm thinking about maybe I'm using the bad parameters? ( GL_RGBA, GL_UNSIGNED_BYTE)

What should I use?


Solution

  • If someone have the same problem, for me adding this line helped:

    int red = (pixels.get(0) & 0xFF);
    

    It get rid off the parts I don't need and now I get the precise color every time.