SFML community forums

Help => System => Topic started by: dotty on January 26, 2012, 11:31:08 pm

Title: IsKeyPressed seems to not fire all the time.
Post by: dotty on January 26, 2012, 11:31:08 pm
Hello, I have a strange thing going on. I've wrote this block of code which monitors the W,A,S and D keys. If the key is up then the state is set to 0, if it's pressed it's 1 and if it's held it's 2. Now, the problem comes if I press all 4 keys at the same time, none of the states change. Also if I hold the keys one by one only 3 of the 4 states change.

If you run the code below and open up your console it logs the keys every frame, then try pressing the keys and you'll notice the issues.

Code: [Select]

#include <SFML/Graphics.hpp>

int main () {

sf::RenderWindow window(sf::VideoMode(640, 480, 32), "SFML Key Test");
window.SetFramerateLimit(60);

bool wKey;
bool aKey;
bool sKey;
bool dKey;

bool wHeld;
bool aHeld;
bool sHeld;
bool dHeld;

int wState;
int aState;
int sState;
int dState;


while (window.IsOpened()){
sf::Event event;
        while (window.PollEvent(event)){
            if (event.Type == sf::Event::Closed){
                window.Close();
}


}


window.Clear();

wKey = sf::Keyboard::IsKeyPressed(sf::Keyboard::W);

if (wKey) {
if (!wHeld) {
wState = 1;
wHeld=true;
}else {
wState = 2;
}
}else {
wHeld = false;
wState = 0;
}

dKey = sf::Keyboard::IsKeyPressed(sf::Keyboard::D);

if (dKey) {
if (!dHeld) {
dState = 1;
dHeld=true;
}else {
dState = 2;
}
}else {
dHeld = false;
dState = 0;
}

sKey = sf::Keyboard::IsKeyPressed(sf::Keyboard::S);

if (sKey) {
if (!sHeld) {
sState = 1;
sHeld=true;
}else {
sState = 2;
}
}else {
sHeld = false;
sState = 0;
}

aKey = sf::Keyboard::IsKeyPressed(sf::Keyboard::A);

if (aKey) {
if (!aHeld) {
aState = 1;
aHeld=true;
}else {
aState = 2;
}
}else {
aHeld = false;
aState = 0;
}

printf("W:%i A:%i S:%i D:%i\n", wState, aState, sState, dState);

window.Display();

}

return EXIT_SUCCESS;

}

Title: IsKeyPressed seems to not fire all the time.
Post by: julen26 on January 26, 2012, 11:55:05 pm
Read about the keyboard buffer (http://en.wikipedia.org/wiki/Keyboard_buffer)
Most keyboards are not designed to handle mor than 3 (or 2) keypresses at the same time.

There's nothing you can do in your code to solve that, just buy a gaming keyboard or a joystick.

Cheers.
Title: IsKeyPressed seems to not fire all the time.
Post by: dotty on January 27, 2012, 09:29:37 am
Thanks for the reply, that makes sense! Didn't realise it was a limitation of my keyboard.