how can I draw a polygon on mouse click in OpenGL?

2.4k views Asked by At

I want my program to draw a polygon when mouse clicks on a button I have created on my screen. Where should I put the draw polygon commands? I understand that I can't put in in my mouse function because its effect is lost the next time my display callback runs and it has to be in my display function. But can I set an if condition in my display function?

1

There are 1 answers

0
Jeff On

Hope this helps you like it helped me. Once you translate the mouse coordinates into something your 3D object can use (see code below) and store it somewhere, you can draw your object in the loop at the stored coordinates using a transform. I initialized my shape, color, etc. in the init function of my OpenGL program but only draw it when I have selected a number on the keyboard and then clicked somewhere in my viewport. Repeating these steps moves/transforms that object to the new coordinates.

void MouseButton(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON)
{
    leftmousebutton_down = (state == GLUT_DOWN) ? TRUE : FALSE;     
    if(leftmousebutton_down)
    {
        cout << "LEFT BUTTON DOWN" << endl;
        //pTransInfo[0].vTranslate  = Vector3( 0.5f, 0.5f, 0.5f ); // center of scene
        GLint viewport[4]; //var to hold the viewport info
        GLdouble modelview[16]; //var to hold the modelview info
        GLdouble projection[16]; //var to hold the projection matrix info
        GLfloat winX, winY, winZ; //variables to hold screen x,y,z coordinates
        GLdouble worldX, worldY, worldZ; //variables to hold world x,y,z coordinates

        glGetDoublev( GL_MODELVIEW_MATRIX, modelview ); //get the modelview info
        glGetDoublev( GL_PROJECTION_MATRIX, projection ); //get the projection matrix info
        glGetIntegerv( GL_VIEWPORT, viewport ); //get the viewport info

        winX = (float)x;
        winY = (float)viewport[3] - (float)y;
        winZ = 0;

        //get the world coordinates from the screen coordinates
        gluUnProject( winX, winY, winZ, modelview, projection, viewport, &worldX, &worldY, &worldZ);

        cout << "coordinates: worldX = " << worldX << " worldY = " << worldY << " worldZ = " <<  worldZ << endl; //THIS IS WHAT YOU WANT, STORE IT IN AN ARRAY OR OTHER STRUCTURE
    }
}

}