The last tutorial showed you how to get keyboard input from the player using a technique called polling. As promised, this tutorial will show you how to get input from the player using the event-driven approach. Polling works pretty good if we only need to check a few keys each frame. But what if we had to check for a lot of keys? We would have a lot of if statements in our input logic. The SDL offers an easy way for us to use the event-driven approach in our video games.
We will be modifying the last tutorial so open it up in your compiler. Scroll down to this section of the code.
// Gain access to keystate array
Uint8 *keys = SDL_GetKeyState(NULL);
Remove those two lines and add this:
// Movement variable; bool move_left = false; bool move_right = false; bool move_up = false; bool move_down = false;
Now, scroll down to the main loop and find these lines:
// Check for messages if (SDL_PollEvent(&event)) {
Add the following after the curly brace:
// Check for keys if (event.type == SDL_KEYDOWN) { SDLKey key = event.key.keysym.sym; if (key == SDLK_LEFT) move_left = true; if (key == SDLK_RIGHT) move_right = true; if (key == SDLK_UP) move_up = true; if (key == SDLK_DOWN) move_down = true; } if (event.type == SDL_KEYUP) { SDLKey key = event.key.keysym.sym; if (key == SDLK_LEFT) move_left = false; if (key == SDLK_RIGHT) move_right = false; if (key == SDLK_UP) move_up = false; if (key == SDLK_DOWN) move_down = false; }
One more modification and we are done. Scroll down and find this block of code:
// Handle input if (keys[SDLK_LEFT]) x -= MOVE_SPEED * ftime; if (keys[SDLK_RIGHT]) x += MOVE_SPEED * ftime; if (keys[SDLK_DOWN]) y += MOVE_SPEED * ftime; if (keys[SDLK_UP]) y -= MOVE_SPEED * ftime;
Change it to this:
// Handle input if (move_left) x -= MOVE_SPEED * ftime; if (move_right) x += MOVE_SPEED * ftime; if (move_down) y += MOVE_SPEED * ftime; if (move_up) y -= MOVE_SPEED * ftime;
Alright, that is it. You should be able to compile and run the program. You will notice that the program behaves exactly like it did before. You might be wondering why we used more lines of code to do the same thing. The answer to that question is to show a different technique for input. Lets say our video game displays a menu when the player presses the F10 button. In the previous tutorial, we would have to check every frame if the F10 button was being pressed. Now, we could just add a check in the event structure to display the menu when the key gets pressed. This is better because we respond to an action taking place instead of checking for an action every frame.
Another note of importance is we are using the same SDLKey definitions as before. This shows the versatility of the SDL library. In the next tutorial you will see how to get mouse input into your game by using the SDL.
See Also:
Back to SDL Tutorial Index
Back to Main Page