Another method which is used for picking objects in a 3D world is color-based picking. In this recipe, we will use the same scene as in the last recipe.
The code for this recipe is in the Chapter2/Picking_ColorBuffer
folder. Relevant source files are in the Chapter2/src
folder.
To enable picking with the color buffer, the following steps are needed:
Disable dithering. This is done to prevent any color mismatch during the query:
glDisable(GL_DITHER);
In the mouse down event handler, read the color value at the clicked position from the color buffer using the
glReadPixels
function:GLubyte pixel[4]; glReadPixels(x, HEIGHT-y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel);
Compare the color value at the clicked point to the color values of all objects to find the intersection:
selected_box=-1; if(pixel[0]==255 && pixel[1]==0 && pixel[2]==0) { cout<<"picked box 1"<<endl; selected_box = 0; } if(pixel[0]==0 &...