What is the best way to detect location / mouse clicks on an object in OpenGL?

I am creating a simple OpenGL 2D game, and I need to know when a player clicks or clicks on the OpenGL primitive. (For example, on GL_QUADS, which serves as one of the slabs ...) There seems to be no easy way to do this outside of brute force or opengl.org's suggestion to use a unique color for each of my primitives that seems a bit hacked. Am I missing something? Thank...

+3
source share
3 answers

You can use OpenGL mode glRenderMode(GL_SELECT). Here is some code that uses it, and it should be easy to follow (look for a method _pick)

( , GL_SELECT C)

( , GL_SELECT " ", CAD 3D-, , - ATI NVidia;))

+1

, OpenGL OpenGL ( , ), , 3D. 2D, , , , , 2D- 2D .

+5

, ( , ). , . opengl, :

// Rendering part
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT);
for(unsigned i=0; i<tileCout; ++i){
    unsigned tileId = i+1; // we inc the tile ID in order not to pick up the black
    glColor3ub(tileId &0xFF, (tileId >>8)&0xFF, (tileId >>16)&0xFF);
    renderTileWithoutColorNorTextures(i);
}

// Let retrieve the tile ID
unsigned tileId = 0;
glReadPixels(mouseX, mouseY, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,
             (unsigned char *)&tileId);
if(tileId!=0){  // if we didn't picked the black 
    tileId--;
    // we picked the tile number tileId
}

// We don't want to show that to the user, so we clean the screen
glClearColor(...); // the color you want
glClear(GL_COLOR_BUFFER_BIT);

// Now, render your real scene
// ...
// And we swap
whateverSwapBuffers(); // might be glutSwapBuffers, glx, ...
+2

Source: https://habr.com/ru/post/1769215/


All Articles