SDL - Manage Keyboard Input

Hi at all! I'm making a simple game just to learn the SDL library. Since the SDL library tells only if a given key is held down or not, I want to do something to get if the keyboard is pressed, held down, released or not pressed at all.
This is the objective I want to achieve:
0 - key not pressed
1 - key pressed
2 - key held down
3 - key released


So, I get the keyboard state:
const Uint8 *keyState = SDL_GetKeyboardState(NULL);
Then make an array containing all the key states as described above:
int keyStates[KEYS_MAX];
And build the array through pointers (I pass respectively my array and the SDL's keyboard state).
getKeyStates(keyStates,keyState);

Now I'm making the player jump, so I need to check the X key for pressing onc. I have thought about a function like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int getKeyStates(int *keyStates, const Uint8 *keyState)
{
    if (keyState[SDL_SCANCODE_X])
    {
        if (keyStates[0] < 2)
            keyStates[0]++;
    }
    else
    {
        if (keyStates[0] == 2)
            keyStates[0] = 3;
        else
            keyStates[0] = 0;
    }
    return *keyStates;
}


The code works, but I want to do this for all the keys and in a nicer way (I mean, instead of using 0, 1, 2, etc... I want to use the same scancode constants of SDL, but there is nothing to check if a given index is a scancode or not without doing a lot of IFs). I know I can achieve this by doing a for cicle up to 255 (because as I know, keys go between 0 and 255):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int getKeyStates(int *keyStates, const Uint8 *keyState)
{
    for (int i = 0; i < 256; i++)
    {
        if (keyState[i] == nullptr)
            continue;
        if (keyState[i])
        {
            if (keyStates[i] < 2)
                keyStates[i]++;
        }
        else
        {
            if (keyStates[i] == 2)
                keyStates[i] = 3;
            else
                keyStates[i] = 0;
        }
    }
    return *keyStates;
}


But SDL_GetKeyboardState returns an array which some its keys in the array just make the program crash when trying to access them... I don't know if I have understood the problem, but nobody teachs me... I'm just learning by myself...
Excuse me for my bad english and thanks in advance!
Last edited on
SDL tells you when a key is pressed down or released by the use of events.

https://wiki.libsdl.org/SDL_Event
Topic archived. No new replies allowed.