Skip to content

Instantly share code, notes, and snippets.

@wldomiciano wldomiciano/test.c
Last active Nov 6, 2017

Embed
What would you like to do?
Demonstração das funções para lidar com eventos de teclado usando SDL 2 com logs no console
// 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
You can’t perform that action at this time.