Events and Global Inputs
Learn the two ways SFML captures Inputs
Events vs Global Inputs
- Question 1 : Has the button been pressed ?
- Question 2 : Is the button currently pressed ?
scenarios | Has the button been pressed ? (Event) | Is the button currently pressed ? (Global Input) |
---|---|---|
Press the button and hold your finger | yes | yes |
Press the button and release your finger | yes | no |
Global Inputs Static Classes
SFML provides three static classes to capture Global Inputs. The class sf::Keyboard can tell you if any of your keyboard buttons is currently pressed, the class sf::Mouse can tell you the states of your mouse (position, wheel, which button is currently pressed) and the class sf::Joystick can tell you the states of any Game Controller connected to your computer. You will learn how to use those three classes in the next tutorials.
- sf::Keyboard : Captures global keyboard inputs
- sf::Mouse : Captures global mouse inputs
- sf::Joystick : Captures global joystick inputs
Event Types
The Events can be classified into four (4) groups. Actually more, but this tutorial will not cover events related to mobile phones.
Group of Events | Description |
---|---|
Window Events | 4 types of Events (closing, resizing, getting focus, losing focus) |
Keyboard Events | 3 types of Events (pressing a button, releasing a button, writing a text) |
Mouse Events | 6 types of Events (pressing a button, releasing a button, moving the mouse, scrolling the wheel, when the mouse enters the window space, when the mouse leaves the window space) |
Joystick Events | 5 types of Events (pressing a button, releasing a button, moving the analog, when the Joystick get connected to the computer when the Joystick get disconnected from the computer) |
The Event Loop
The code below is used in our Engine class to retrieve and process Events. As you can see we are using a loop called the Event Loop.
sf::Event event; while(m_RenderWindow.pollEvent(event)) { //Capture user inputs here if(event.type == sf::Event::Closed) { m_RenderWindow.close(); } //Update game here } //Redner Game here (outsite of the Event Loop)
When an event occurs, SFML will store it inside a queue (the Event Queue), see image below. The queue is a FIFO table (First In, First Out). When the method pollEvent() is called, the least recent event will be removed from the queue and returned to you. The idle scenario would be to process events as soon as they are emitted by the user, but that’s not always possible, sometimes several events accumulate before you get the time to process them. In this case, we use the Event Loop to process all the accumulated events before rendering our Game
- sf::Event : a class storing all information related to an event
- pollEvent(event) : a method used to retrieve the oldest event stored in the SFML Event Queue (FIFO table)
- Event Loop : used to cycle through all available events till the Event Queue becomes empty.
