Reputation: 17
I'm using SDL 2.0, and I can't get SDL_GetKeyboardState
to work as expected. The player should move up and down, but this is not happening.
void Movements() {
const Uint8 *currentKey = SDL_GetKeyboardState(NULL); // Point has to be defined once
if (currentKey[SDLK_w]){
PlayerPaddle.y = PlayerPaddle.y+2;
}
if (currentKey[SDLK_s]){
PlayerPaddle.y = PlayerPaddle.y+2;
}
}
int main(int argc, char* args[]) {
main_menue();
bool running = true;
while (running == true) {
SDL_PollEvent(&occur);
if (occur.type == SDL_QUIT) { // Closes the window, if user stops running
running = false;
}
Movements();
}
}
I also tried to pump up the event loop with PumpEvents
, but still can't read the current state of a key. I also found this on stackoverflow (SDL_GetKeyboardState not working), but the answers there did not help me find a solution. Did I miss something here? Am I really blind and misunderstood something?
Upvotes: 0
Views: 2025
Reputation: 2917
Assuming SDL_Init()
and other declarations were just removed when pasting here.
First, you are not using correct indexes. As explained in the documentation here : "Indexes into this array are obtained by using SDL_Scancode values." But you are using SDL_Keycode values.
The other problem is that you are using the non-blocking SDL_PollEvent
and calling Movements()
at each iteration, and don't have any kind of blocking or waiting in your loop. This will use 100% CPU, running as fast as possible, and you'll end up with a pretty high y
value ...
Instead of the array returned by SDL_GetKeyboardState
you could use the key events. If occur.type
is for instance SDL_KEYDOWN
, occur.key.keysym.sym
is the SDL_Keycode
of the pressed key. Look at the documentation of SDL_Event
and other event types for the details.
You should also add a SDL_Delay
to your loop.
Another way is to use SDL_WaitEvent
which only returns when an event occurs. Then you process the event, if it is a key press do some action depending on the key, etc ...
Upvotes: 1