c++graphicskeyboardglutcurves

Detect only one keypress in C++


I'm trying to use the glut framework to handle keypresses for a game I'm writing in c++. When a specific key is pressed, I want to start drawing a new curve and so I create a new curve and add it to my container of curves. However, when I use onKeyboard and debug I see that this function is called over and over when a key is pressed, not just on the initial press. Therefore, it's creating about 12 curves every time a key is pressed. My code for onKeyboard is below. Any help would be appreciated greatly!

void onKeyboard(unsigned char key,int x, int y) {
    keysPressed[key] = true;
    switch (key) {
            case 'l':
                curvesContainer.addCurve(new lCurve());
                break;
            case 'p':
                curvesContainer.addCurve(new pCurve());

    }
    glutPostRedisplay();
}

Solution

  • You would simply check if keyPressed[key] is already true, and only add your curve if it is false.

    void onKeyboard(unsigned char key,int x, int y) 
    {
        if (keysPressed[key] == false)
        {        
            keysPressed[key] = true;
    
            switch (key) 
            {
                case 'l':
                    curvesContainer.addCurve(new lCurve());
                    break;
                case 'p':
                    curvesContainer.addCurve(new pCurve());
                    break;
            }
        }
    
        glutPostRedisplay();
    }
    

    You will additionally need to clear keysPressed[key] in an onKeyUp event, using glutKeyboardUpFunc

    void onKeyUp(unsigned char key,int x, int y) 
    {
        keysPressed[key] == false;       
    }