Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: IsKeyPressed seems to not fire all the time.  (Read 3865 times)

0 Members and 2 Guests are viewing this topic.

dotty

  • Jr. Member
  • **
  • Posts: 56
    • View Profile
IsKeyPressed seems to not fire all the time.
« 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;

}


julen26

  • Jr. Member
  • **
  • Posts: 89
    • View Profile
    • http://julen26.blogspot.com
IsKeyPressed seems to not fire all the time.
« Reply #1 on: January 26, 2012, 11:55:05 pm »
Read about the 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.

dotty

  • Jr. Member
  • **
  • Posts: 56
    • View Profile
IsKeyPressed seems to not fire all the time.
« Reply #2 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.

 

anything