Using OpenGL /GLUT how would I detect if two keys are held down at the same time?

epochwolf picture epochwolf · May 15, 2009 · Viewed 7.7k times · Source

Using OpenGL /GLUT how would I detect if two keys, say 'a' and 'j' are held down at the same time?

(This program needs to compile with OSX GCC, Windows GCC, Windows VS2005 so no OS dependent hacks please.)

Answer

Trillian picture Trillian · May 15, 2009

Try the following:

  1. Use glutIgnoreKeyRepeat to only get physical keydown/keyup events
  2. Use glutKeyboardFunc to register a callback listening to keydown events.
  3. Use glutKeyboardUpFunc to register a callback listening to keyup events.
  4. Create a bool keystates[256] array to store the state of the keyboard keys.
  5. When receiving an event through your keydown callback, set keystates[key] = true.
  6. When receiving an event through your keyup callback, set keystates[key] = false.
  7. In your run loop, test if (keystates['a'] || keystates['A']) && (keystates['j'] || keystates['J']).

Look in that direction. Although I haven't tested it, it should work. You might also need glutSpecialFunc and glutSpecialUpFunc to receive messages for 'special' keys.

Also, be aware that GLUT is really old stuff and that there are much nicer alternatives.