SFML community forums

Help => Window => Topic started by: Antonio9227 on December 03, 2013, 03:55:44 pm

Title: Keyboard question
Post by: Antonio9227 on December 03, 2013, 03:55:44 pm
Hello guys, I am still working on my first SFML game and I have another question for you today.This time I have a problem with the keyboard.

My code looks something like this:
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::A))
//Move Left
It works as supposed, the object moves to left, but it also works when I'm outside of the render window. For example if I leave the game open and go write some text somewhere, every time I use "ASDW" the object moves. It's like sensing the keys globally.

Well since I test if the key is pressed, this make total sense (the game sits back and tests if keys are pressed).

 Is there any better way of doing this?
Title: Re: Keyboard question
Post by: wintertime on December 03, 2013, 04:05:20 pm
You may want to read http://sfml-dev.org/tutorials/2.1/window-events.php there are all events explained.
I think you only get key events when the window is activated.
If you want to keep using isKeyPressed instead you may want to check for focus events and only react to input when your window is active.
Title: Re: Keyboard question
Post by: Njifra on December 06, 2013, 05:32:16 pm
Well, you should use something like this:

int main()
{
    bool isPaused = false;
    //[CODING] Here is probably your window coding.
    while (window.isOpen())
    {
         while (window.pollEvent(event))
         {
               if (event.type == sf::Event::LostFocus)
                   isPaused = true;
               else if (event.type == sf::Event::GainedFocus)
                   isPaused = false;
         }
         if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && !isPaused)
         {
             //move left
         }
    }
    return 0;
}

I hope it helps