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

Author Topic: Keyboard question  (Read 2004 times)

0 Members and 1 Guest are viewing this topic.

Antonio9227

  • Newbie
  • *
  • Posts: 25
    • View Profile
Keyboard question
« 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?

wintertime

  • Sr. Member
  • ****
  • Posts: 255
    • View Profile
Re: Keyboard question
« Reply #1 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.

Njifra

  • Guest
Re: Keyboard question
« Reply #2 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

 

anything