Search code examples
c++openglglut

One mouse click is registered twice C++ / GLUT


I have to make some transformation with left mouse click. This is part of my code:

void mouse(int button, int state, int x, int y) {
if(button == GLUT_LEFT_BUTTON && v*p + xk <= 34 && v*p + yk <= 34 && v*p - xk <= 34 && v*p - yk <= 34) {
    std::cout << "Resized" << std::endl;
    p += 0.02;

    }
    glutPostRedisplay();
}

But when I do click once on the screen, it prints "Resized" twice. What could be the issue here?


Solution

  • The glutMouseFunc() is invoked once, when the mouse is pressed and once when the mouse is released.
    When the mouse is pressed, then the actual state argument is GLUT_DOWN. When the mouse is released then the argument is GLUT_UP.

    Additionally test if state == GLUT_DOWN:

    void mouse(int button, int state, int x, int y) {
    
        if (state == GLUT_DOWN &&                      // <----
            button == GLUT_LEFT_BUTTON &&
            v*p + xk <= 34 && v*p + yk <= 34 && v*p - xk <= 34 && v*p - yk <= 34) {
    
            std::cout << "Resized" << std::endl;
            p += 0.02;
        }
        glutPostRedisplay();
    }