c++ - SDL_Keycodes are too big for storage -
while searching methods of detecting multiple keys @ once in sdl 2, came across piece of code sdl 1.x:
//author: rob loach // global key buffer bool keys[256]; while(sdl_pollevent(&mainevent)) { if(mainevent.type == sdl_keydown) { keys[mainevent.key.keysym.sym] = true; } else if(mainevent.type == sdl_keyup) { keys[mainevent.key.keysym.sym] = false; } }
i tried implementing in sdl2 , std::array<bool, 256>
, had segmentation fault: 11
button.
that's when looked @ this: https://wiki.libsdl.org/sdlkeycodelookup.
most of 'special' keys including arrow, function, symbols, , on have decimal representations in billions.
even simple code printf("%d\n", e.key.keysym.sym);
on, button gives:
1073741906 segmentation fault: 11
i on mac, if makes difference error codes.
so, solutions there in sdl 2?
first of all, bool
s don't default in c++
, need initialize them. fact appear true
they're byte
in size. means have size between 0
, 255
inclusive. 0
mean false
255 / 256
chance of true
.
as solution, define std::map
:
std::map<sdlkey, bool> keymap;
an std::map
empty, need check items exists when try up.
bool iskeydown(sdlkey key) { // element auto = keymap.find(key); if (it == keymap.end()) // no element found, means key hasn't been pressed return false; // 'it' iterator, use * return value return it->second; }
when try set item, automtically created if doesn't exists :
bool setiskeydown(sdlkey key, bool isdown) { keymap[key] = isdown }
so fact std::map
empty means don't need fill it. can if want to, it's not required array.
Comments
Post a Comment