SFML community forums

Help => System => Topic started by: wuw on July 07, 2019, 11:12:13 pm

Title: [SOLVED] Can't always detect when more then two keys being pressed.
Post by: wuw on July 07, 2019, 11:12:13 pm
Hello!

I am trying to detect any input from the keyboard. I do this by having an array of bools, one bool for every key. When a button is pressed the corresponding bool is set to true and when released it's set to false. Everything seems to work fine until three or more keys are pressed, it's only some combination of keys that work. For example, holding down the keys A, S, and O work fine while A, S, and H do not work and only prints the number for A and S.

Code:

int findPressedButten();
void keyPressed();
void keyReleased();
void printPressedKeys();

sf::Event event;
bool keysPressed[sf::Keyboard::KeyCount];

int main()
{
        sf::RenderWindow window(sf::VideoMode(600.0f, 600.0f), "SFML project");

        while (window.isOpen())
        {
                while (window.pollEvent(event))
                {
                        switch (event.type) {
                        case sf::Event::KeyPressed:
                                keyPressed();
                                break;

                        case sf::Event::KeyReleased:
                                keyReleased();
                                break;
                        }
                }

                printPressedKeys();

        }
}

int findPressedButten()
{
        for (int i = 0; i < sf::Keyboard::KeyCount; i++) {
                if (event.key.code == i) {
                        return i;
                }
        }

        return -1;
}

void keyPressed()
{
        int index = findPressedButten();

        if (index != -1)
                keysPressed[index] = true;
}

void keyReleased()
{
        int index = findPressedButten();

        if (index != -1)
                keysPressed[index] = false;
}

void printPressedKeys()
{
        bool keyWasPressed = false;

        for (int i = 0; i < sf::Keyboard::KeyCount; i++) {
                if (keysPressed[i]) {
                        keyWasPressed = true;
                        std::cout << i << " ";
                }
        }

        if (keyWasPressed)
                std::cout << std::endl;
}
 
Title: Re: Can't always detect when more then two keys being pressed.
Post by: G. on July 07, 2019, 11:27:33 pm
It's a mechanical limitation, it's called keyboard ghosting.
I don't think you can do anything against it but choosing wisely the keys you use in your application.
Title: Re: Can't always detect when more then two keys being pressed.
Post by: wuw on July 07, 2019, 11:34:01 pm
It's a mechanical limitation, it's called keyboard ghosting.
I don't think you can do anything against it but choosing wisely the keys you use in your application.

Ow, interesting. Thanks for the answer!