Last active
August 29, 2015 14:11
-
-
Save madaan/6f10b3539274ef75c952 to your computer and use it in GitHub Desktop.
SDL2 code for capturing multiple keypresses in one go, based on http://www.programmersranch.com/2014/02/sdl2-keyboard-and-mouse-movement-events.html
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
#include <SDL.h> | |
#include <iostream> | |
using namespace std; | |
int main(int argc, char ** argv) | |
{ | |
bool quit = false; | |
SDL_Event event; | |
int x = 288; | |
int y = 208; | |
// init SDL | |
SDL_Init(SDL_INIT_VIDEO); | |
SDL_Window * window = SDL_CreateWindow("SDL2 Keyboard/Mouse events", | |
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0); | |
SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0); | |
SDL_Surface * image = SDL_LoadBMP("spaceship.bmp"); | |
SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, | |
image); | |
SDL_FreeSurface(image); | |
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); | |
while (!quit) | |
{ | |
SDL_Delay(20); | |
SDL_PollEvent(&event); | |
switch (event.type) | |
{ | |
case SDL_QUIT: | |
quit = true; | |
break; | |
} | |
/*Multiple Key Capture Begins*/ | |
const Uint8 *state = SDL_GetKeyboardState(NULL); | |
/*Verbose for no particular reason*/ | |
bool up = state[SDL_SCANCODE_UP], | |
left = state[SDL_SCANCODE_LEFT], | |
right = state[SDL_SCANCODE_RIGHT], | |
down = state[SDL_SCANCODE_DOWN]; | |
if(up) y--; | |
if(down) y++; | |
if(right) x++; | |
if(left) x--; | |
SDL_Rect dstrect = { x, y, 64, 64 }; | |
SDL_RenderClear(renderer); | |
SDL_RenderCopy(renderer, texture, NULL, &dstrect); | |
SDL_RenderPresent(renderer); | |
} | |
// cleanup SDL | |
SDL_DestroyTexture(texture); | |
SDL_DestroyRenderer(renderer); | |
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