SFML 2.0 Keyboard Event

I am trying to get key input in SFML 2, in SFML 1.6 im using

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

But I do not know how to do this in SFML 2.

+4
source share
1 answer

If you don’t need to worry about typing the keyboard in real time, you can use an approach very similar to the 1.6ML code you provided. In your application event 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 processing is good when you need to ensure that your application has focus when the user presses a key, because key events are not generated otherwise. It is also great when a key question is pressed infrequently. You can see an example of this from the SFML 2.0 tutorials here in the section "Events with KeyPressed and KeyReleased": http://sfml-dev.org/tutorials/2.0/window-events.php

On the other hand, you may really need access to the keyboard in real time. To do this, use the SFML 2.0 keyboard class as follows:

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

In real-time input, you gain access to the state of the input device at that particular point in time. This is convenient because you do not need to block all key checks in the event loop. The disadvantage of this approach is that SFML simply reads the state of the keyboard, your event processing code can still be executed if the application does not have focus, minimized, etc. You can find a tutorial on all real-time inputs here: http://sfml-dev.org/tutorials/2.0/window-inputs.php

Be careful when choosing an event processing method or real-time. For an example game, consider a situation where a character fires a machine gun when a user holds a space. If you handle a space in the event loop, the machine gun doesn’t work correctly, like a semi-automatic one, because there is a delay between sf::Event::KeyPressed events for the same key, even if the user holds the key down. If you handle the space by checking the keyboard input in real time, the machine gun will fire repeatedly, as expected.

+14
source

Source: https://habr.com/ru/post/1413634/


All Articles