Last active
November 6, 2017 16:15
-
-
Save wldomiciano/26ca464b697e61d6bc85f2b07026631e to your computer and use it in GitHub Desktop.
Demonstração das funções para lidar com eventos de teclado usando SDL 2 com logs no console
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Testado no MinGW64 | |
// gcc -Wall -Wextra -Wpedantic -Wno-unused-parameter game.c `sdl2-config --cflags --libs` | |
#include <SDL.h> | |
SDL_bool quit = SDL_FALSE; | |
// A tecla está pressionada? | |
SDL_bool isKeyPressed(int key) { | |
return SDL_GetKeyboardState(NULL) [key]; | |
} | |
// Variável global | |
Uint8 keyStates[SDL_NUM_SCANCODES]; | |
// Reinicia estados | |
void resetKeyStates() { | |
for (size_t i = 0; i < SDL_NUM_SCANCODES; i++) | |
keyStates[i] = 0; | |
} | |
// A tecla foi pressinada? | |
Uint8 wasKeyPressed(int key) { | |
return keyStates[key] == 1; | |
} | |
// A tecla foi liberada? | |
Uint8 wasKeyReleased(int key) { | |
return keyStates[key] == 2; | |
} | |
void handleInput() { | |
resetKeyStates(); | |
SDL_Event event; | |
while (SDL_PollEvent(&event)) { | |
switch (event.type) { | |
case SDL_QUIT: | |
quit = SDL_TRUE; | |
break; | |
case SDL_KEYDOWN: | |
keyStates[event.key.keysym.scancode] = !event.key.repeat; | |
break; | |
case SDL_KEYUP: | |
keyStates[event.key.keysym.scancode] = 2; | |
break; | |
} | |
} | |
} | |
int main(int argc, char *argv[]) { | |
SDL_Init(SDL_INIT_VIDEO); | |
SDL_Window* window = SDL_CreateWindow("Window Title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0); | |
while ( !quit ) { | |
handleInput(); | |
if ( isKeyPressed(SDL_SCANCODE_A) ) | |
SDL_Log("A is pressed!"); | |
if ( wasKeyPressed(SDL_SCANCODE_SPACE) ) | |
SDL_Log("Space was pressed!"); | |
if ( wasKeyReleased(SDL_SCANCODE_SPACE) ) | |
SDL_Log("Space was released!"); | |
} | |
SDL_DestroyWindow(window); | |
SDL_Quit(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment