Here is my code that's part of the main game loop:
// ResetKeyState stores currentKeyState in previousKeyState
// and then clears currentKeyState
engine.ResetKeyState();
// Fill currentKeyState
while (SDL_PollEvent(&e) != 0)
{
// Call input to notify
engine.Input(e);
if (e.type == SDL_QUIT)
engine.Quit();
}
// Return control to programmer for implementation
engine.EngineUpdate();
// Draw a pretty picture
engine.EngineDraw();
and then to handle the input I have Input(e)
void Engine::Input(SDL_Event e)
{
switch (e.type)
{
case SDL_KEYDOWN:
KeyIsDown(e.key.keysym.sym);
break;
case SDL_KEYUP:
KeyIsUp(e.key.keysym.sym);
break;
default:
break;
}
}
KeyIsDown
stores the boolean state in an array as a true value.
KeyIsUp
stores a false value.
Then later, I thought I would be able to do this to get a single input.
if (IsCurrentKeyDown('a') && !IsPreviousKeyDown('a'))
IsCurrentKeyDown
and IsPreviousKeyDown
just get data from their arrays
bool currentKeyState[INPUT_SIZE];
bool previousKeyState[INPUT_SIZE];
This way if you've are currently pressing the key but the value hasn't yet been stored it takes input once.
IE: You press the key so currentKeyDown
is true and previousKeyDown
is false
until next update where currentKey
gets passed to previousKey
and the statement is then false
. It's how Monogame and XNA do it so I figured I'd implement it here.
But it didn't work. I put a break point with a hit counter on it and it would hit it more than once per press. What am I doing wrong?
SDL_KEYDOWN
per frame? \$\endgroup\$if (IsCurrentKeyDown('a') && !IsPreviousKeyDown('a'))
type of code is used to detect stuff like 'the event just happened', in this case, has the key just went down. As @Tyyppi_77 points out, you'll need another key array to store the state as well. \$\endgroup\$