Alkatell
Alkatell

Reputation: 45

2 keys at the same time SDL CodeBlocks

So, i'm coding a choplifter in C and my question is: How can i manage two keys pressed at the same time with the SDL? I tried with two switches but there's nothing to do, it won't work :/

Is it possible to do it with the SDL?

Upvotes: 1

Views: 1195

Answers (3)

Donald Duck
Donald Duck

Reputation: 8902

If what you want to do is supporting pressing CTRL and another button (for example CTRL+A), you can use unicode. The advantage is that it's very simple to use and compatible with AZERTY keyboards. So if you want to do this to be able to support CTRL+something, I recommend using this. However, for any other use, it doesn't work so use one of the other answers. This is an example about how to use it:

switch(event.type){
    case SDL_KEYDOWN:
        SDL_EnableUNICODE(1);
        switch(event.key.keysym.unicode){
            case 1:   //CTRL+A
                //code
                break;
            case 97:  //A
                //code
                break;
        }
}

To get the codes for each combination of keys, write this code in your program after making sure that there isn't any SDL_EnableKeyRepeat in your code (or if there is, insert temporarily // in front of it, because otherwise you will get long repetitions of the same code):

fprintf(stderr,"%d",event.key.keysym.unicode);

and the code for the combination in question is in the file stderr.txt in the same folder as the executable.

Upvotes: 0

Scott
Scott

Reputation: 448

When I do this, personally I like to use SDL_GetKeyState to check each key on the keyboard manually using something similar to the following code:

int *keystates;

keystates = SDL_GetKeyState(NULL);
if (keystates[SDLK_a]) {
    a_key_pressed = true;
} else {
    a_key_pressed = false;
}
if (keystates[SDLK_b]) {
    b_key_pressed = true;
} else {
    b_key_pressed = false;
}

A full list of all the keynames in SDL is avaliable at http://www.libsdl.org/docs/html/sdlkey.html#AEN4720

ideally you could make this into a function to check any key easily like this: (Not tested, but concept is correct)

BOOL CheckKey(int keyname) {
    int *keystates = SDL_GetKeyState(NULL);
    if (keystates[keyname]) {
        return TRUE;
    }
    return FALSE;
}

Upvotes: 0

James Hurley
James Hurley

Reputation: 762

An example: If you were, say trying to read if both 'a' and 'b' were pressed at the same time, you could run a loop to check for events as usual and have Boolean values called a_true and b_true and check at the end of the loop if both are true. You could have a key pressed check to make them true and also a key released check to make them false. Without code I don't think anyone can give a more descriptive answer.

Upvotes: 1

Related Questions