Keyboard Event SFML 2.0

Mete picture Mete · May 22, 2012 · Viewed 9.6k times · Source

Im trying to get the key input in SFML 2, in the SFML 1.6 im using

   while (App.GetEvent(Event))
       {
          if (App.GetInput().IsKeyDown(sf::Key::Down)) { dir='d'; }
    }

But i have no idea how to do this in SFML 2.

Answer

Armory picture Armory · Aug 9, 2012

When you don't need to worry about real-time keyboard input, you can use an approach very similar to the SFML 1.6 code you provided. In your application's event processing loop, you can do something like this:

sf::Event event;
while (mWindow.pollEvent(event))
{
    if (event.type == sf::Event::KeyPressed)
    {
        if (event.key.code == sf::Keyboard::Escape)
        {
            // Do something when Escape is pressed...
        }
        if (event.key.code == sf::Keyboard::W)
        {
            // Do something when W is pressed...
        }

        // And so on.
    }
}

This type of input handling is nice when you must guarantee your application has focus when the user presses the key, as key events aren't generated otherwise. It is also great for when the key in question is pressed infrequently. You can check out an example of this from the SFML 2.0 tutorials here, under the section titled "The KeyPressed and KeyReleased events": http://sfml-dev.org/tutorials/2.0/window-events.php

On the other hand, you may actually need access to real-time keyboard input. To do this, use SFML 2.0's Keyboard class like this:

if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
    // 'W' is currently pressed, do something...
}

With real-time input, you are accessing the state of the input device at that particular point in time. This is handy because you do not have to lump all your key checks in your event processing loop. A disadvantage of this approach is since SFML is just reading the state of the keyboard, your event handling code can still execute if the application doesn't have focus, is minimized, etc. You can find a tutorial on all the real-time inputs here: http://sfml-dev.org/tutorials/2.0/window-inputs.php

Be careful in choosing the event processing vs. real-time approach. For a game example, consider a situation where a character fires a machine gun when the user holds down the space bar. If you handle the space bar in the event processing loop, the machine gun will incorrectly fire like a semi-automatic since there is a delay between sf::Event::KeyPressed events for the same key, even if the user is holding the key down. If you handle the space bar by checking with real-time keyboard input, the machine gun will fire repeatedly, as expected.