nounoursnoir nounoursnoir - 1 year ago 55
C Question

No SDL event for space keypress if down+right or up+left already pressed

I am experimenting movements in a 2D game in SDL, and it works fine. However when I add the possibility for the character to shoot by pressing

SPACE
, I face a strange bug: If down and right keys or up and left keys are already pressed, no event is created when pressing
SPACE
. In other cases, an event is created, as it should be.

Here is the loop I use to get some events:

while (on == 1)
{
SDL_PollEvent(&event);
switch (event.type)
{
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_ESCAPE:
on = 0;
break;
case SDLK_UP:
shooter1.dir[0] = 1; // shooter1 is an instance of a structure that
// contains a position and an array representing
// 4 directions (down, up, left, right)
break;
case SDLK_DOWN:
shooter1.dir[1] = 1;
break;
case SDLK_LEFT:
shooter1.dir[2] = 1;
break;
case SDLK_RIGHT:
shooter1.dir[3] = 1;
break;
case SDLK_SPACE: // Eventually, the program does not go in this
// case, even though the SPACE key is pressed
fprintf(stderr, "SPACE PRESSED\n");
break;
default:
break;
}
break;
case SDL_KEYUP:
switch (event.key.keysym.sym)
{
case SDLK_UP:
shooter1.dir[0] = 0;
break;
case SDLK_DOWN:
shooter1.dir[1] = 0;
break;
case SDLK_LEFT:
shooter1.dir[2] = 0;
break;
case SDLK_RIGHT:
shooter1.dir[3] = 0;
break;
default:
break;
}
break;
default:
break;
}
event.type = 0;
get_new_positions(&shooter1);
SDL_BlitSurface(background, NULL, screen, &background_pos);
blit_shooter(screen, &shooter1);
SDL_Flip(screen);
}


Any idea of what this behavior is due to?

Answer Source

This is almost certainly a hardware limitation. Quoting from the relevant Wikipedia page, emphasis added:

Certain high-end keyboards have "n-key rollover". This means that each key is scanned completely independently by the keyboard hardware, so that each keypress is correctly detected regardless of how many other keys are being pressed or held down at the time. [...]

However, to reduce cost and design complexity, most computer keyboards do not isolate all keys in this way. Instead, they use a matrix of key switches, without any isolation diodes, that assumes that only a limited number of keys will be held down at any given time. With these keyboards, pressing as few as three keys can cause ghosting effects, although care is taken when laying out the matrix arrangement that this does not happen for common modifier key combinations.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download