Hey guys,
To manage single key presses I use something I learned about in a class on writing operating systems. It's a variation on a concept called a semaphore. Basically you "lock" the resource while it is in use and only "unlock" it when it isn't being used anymore.
Here's a quick code sample to handle single key presses of the spacebar. You could easily expand this to have an array of semaphores for each key so that any key pressed would only act once until it has been released and repressed.
I've included two samples with minor differences to illustrate the importance of the code structure. If you trace the code with pen and paper it starts to make sense why the first one works and the second doesn't.
//----------------------------------------------------------------------------------------------------------------------
// This example works (pay attention to the structure of the conditionals. The nesting is important.
//----------------------------------------------------------------------------------------------------------------------
// is 0 when space isn't held down, 1 otherwise
int space_semaphore = 0;
if (dbSpaceKey() == 1) {
// if the space key wasn't previously held down, then perform our action
if (space_semaphore == 0) {
// indicate that we're holding down the space key
space_semaphore = 1;
// do action related to the space key
... put stuff here ...
}
} else {
space_semaphore = 0;
}
//----------------------------------------------------------------------------------------------------------------------
// This example doesn't work. Notice that the semaphore is checked as part of the same condition as the keypress. This
// is incorrect and will result in your semaphore having no effect whatsoever.
//----------------------------------------------------------------------------------------------------------------------
// is 0 when space isn't held down, 1 otherwise
int space_semaphore = 0;
if ((dbSpaceKey() == 1) && (space_semaphore == 0)) {
// indicate that we're holding down the space key
space_semaphore = 1;
// do action related to the space key
... put stuff here ...
} else {
space_semaphore = 0;
}
Hope this helps,
-Frank