SDL event check

Hi all,
I am experimenting with SDL, and I made a very small game (it actually can't be called a game :) ). It simply checks for key input, and if the arrow keys are pressed, the x and y of the sprite are changed accordingly. Then the sprite is blitted. My problem is: when I press for example the up key once, the sprite moves 5 pixels up, which is correct. But when I hold the up key (or any other arrow key), the sprite stays where it is and doesn't move. Here is the part of the code I think the error is in:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    bool done = false;

    while ( !done ) {
        while ( SDL_PollEvent( &event ) ) {
            if ( event.type == SDL_QUIT ) {
                done = true;
            }

            if ( event.type == SDL_KEYDOWN ) {
                if ( event.key.keysym.sym == SDLK_ESCAPE ) {
                    done = true;
                }

                if ( event.key.keysym.sym == SDLK_UP ) {
                    player.y -= 5;
                }

                if ( event.key.keysym.sym == SDLK_DOWN ) {
                    player.y += 5;
                }

                if ( event.key.keysym.sym == SDLK_LEFT ) {
                    player.x -= 5;
                }

                if ( event.key.keysym.sym == SDLK_RIGHT ) {
                    player.x += 5;
                }
            }
        }

        SDL_FillRect( screen, NULL, 0 );

        pos.x = player.x - ( player.texture->w / 2 );
        pos.y = player.y - ( player.texture->h / 2 );

        SDL_BlitSurface( player.texture, NULL, screen, &pos );

        SDL_Flip( screen );
    }

I first had all those arrow-press checking ifs in a switch, and I tried to solve the problem like this, but the problem still wasn't solved. I also changed the bottom 4 ifs to else ifs, but still the problem. Any help?
Last edited on
Solved :) I added SDL_EnableKeyRepeat().
If you want to check if a key is down you can use SDL_GetKeyState that returns a pointer to an array with information for all keys.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Uint8* keystate = SDL_GetKeyState(NULL);
if (keystate[SDLK_UP])
{
	player.y -= 5;
}
if (keystate[SDLK_DOWN])
{
	player.y += 5;
}
if (keystate[SDLK_LEFT])
{
	player.x -= 5;
}
if (keystate[SDLK_RIGHT])
{
	player.x += 5;
}

Topic archived. No new replies allowed.