user1902544
user1902544

Reputation: 55

Read pixel colours with OpenGL?

I am trying to do collisions by reading the pixel colour of the pixel beside object, but I am confused about how to accomplish this.

I read about glreadpixels, but I don't really understand the parameters, especially the last one, which is supposed to be of type ByteBuffer. Can anyone explain to me how can I accomplish this, or maybe a better way to do simple collision detection?

Upvotes: 2

Views: 1188

Answers (1)

Alex Musk
Alex Musk

Reputation: 158

This is definately not the easiest or most efficient way to do collision detection however to answer your question;

ByteBuffer RGB = ByteBuffer.allocateDirect(3); //create a new byte buffer (r, g, b)

int x=1, y=1;

GL11.glReadPixels(x, y, //the x and y of the pixel you want the colour of
1, 1,                   //height, width of selection. 1 since you only want one pixel
GL11.GL_RGB,            //format method uses, get red green and blue
GL11.GL_UNSIGNED_BYTE,  //how the method is performed; using unsigned bytes
RGB);                   //the byte buffer to write to

float red, green, blue;

red = RGB.get(0)/255f,   //get the first byte
green = RGB.get(1)/255f, //the second
blue = RGB.get(2)/255f;  //and third

For the best way to do collision detection a quick search pulled up: Basic Collision Detection in 2D – Part 1.

It looks quite useful.

Upvotes: 3

Related Questions