Reader small image

You're reading from  SFML Game Development

Product typeBook
Published inJun 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781849696845
Edition1st Edition
Languages
Tools
Right arrow
Authors (5):
 Artur Moreira
Artur Moreira
author image
Artur Moreira

Artur Moreira is a game development enthusiast who ultimately aims to start a new game development company in his home country. He has been programming games and game-related software for over 4 years. Most of the effort in that time was put in creating an open source game-making library with lots of flexibility and portability. The library is called Nephilim and is known for supporting all major desktop and mobile operating systems, making game development fully crossplatform and fast. Alongside this big project, he keeps making his own prototypes and games for educational and commercial purposes. Aside from the programming, he also puts some focus in creative areas such as 3D modeling, digital painting, and music composing.
Read more about Artur Moreira

 Henrik Vogelius Hansson
Henrik Vogelius Hansson
author image
Henrik Vogelius Hansson

Henrik Vogelius Hansson has always been in love with both games and programming. He started his education fairly early and continued on into the indie scene with Defrost Games and their game Project Temporality. The next company that hired him was Paradox Development Studio where he got to work on titles such as Crusader Kings 2. Beside the game companies, Henrik has also been very active in the SFML community and has even provided a binding for Ruby called rbSFML.
Read more about Henrik Vogelius Hansson

Jan Haller
Jan Haller
Henrik Valter Vogelius
Henrik Valter Vogelius
View More author details
Right arrow

Chapter 4. Command and Control – Input Handling

In the previous chapter, we talked about how to implement the world our game takes place in and the different objects that the world is made up of. In this chapter, we will focus on how to give the player the power to manipulate this world.

In this chapter we aim to learn:

  • SFML events and their purpose as input

  • SFML real-time input and its difference from events

  • A command-based communication system to deliver events in our world

  • How to dynamically bind keys at runtime

In the previous chapters, we have used events to manage input, but we have not really delved into what they are or what they are meant to be used for. That is the first point of this chapter. After that, we will look at more concepts of input than just simply events.

Polling events


Generally speaking, events are objects that are triggered when something happens; mostly related to the user input. Events are a construct in the underlying operating system. On top of them, SFML provides a nice abstraction layer that is easier to use and cross-platform. SFML goes with a polling design to have you work with events. When an input occurs, the operating system reports it to the application. SFML processes this input, converts it into the corresponding SFML event type, and puts it into a queue of waiting events. In your actual application code, you extract events from this queue using the sf::Window::pollEvent() function (note that sf::Window is the base class of sf::RenderWindow, without the rendering functionality). The pollEvent() function signature is a bit interesting:

bool sf::Window::pollEvent(sf::Event& event);

Now this is a bit special and might not be self-explanatory. The problem with pollEvent() is that we want to receive two different values. We...

Getting the input state in real time


Now, we have gone through many varieties of events. A problem with events is that they report once when the state changes, but you cannot continuously ask them how the state of the input devices look right now.

You can solve this by book keeping yourself, which we have done in the examples preceding this chapter. But SFML, in an effort to make input management easier, has implemented classes that let you access these states in real time whenever you want from wherever you want. We will use the notion of real-time input to denote this alternative method of handling user input.

The three classes sf::Joystick, sf::Keyboard, and sf::Mouse can provide almost the same information that the event-based counterparts do, but with some minor variations. They are summarized here and their difference to the events is shown; we recommend visiting the SFML documentation for more details on them. The three classes contain only static functions, so they are not designed...

Playing nice with your application neighborhood


Now what we learned in the last part is indeed handy, but it has got its problem. What if the user tabs out and tries to interact with the other applications that are running in the background? We would be constantly forcing the mouse back to the center of our window, making it impossible to do anything else than playing our game.

Believe it or not, this is actually very annoying for a lot of people, including ourselves. When we are debugging our application, this behavior will make it impossible to work with the IDE in the background. We have to detect when the user doesn't want to interact with us anymore and behave properly.

This is where events come in again. If you remember, we had the event types sf::Event::GainedFocus and sf::Event::LostFocus that notify the application as soon as the window gains or loses focus:

void Game::processEvents()
{
    sf::Event event;
    while(mWindow.pollEvent(event))
    {
        if (event.type == sf::Event...

A command-based communication system


Up to now, you have seen how events and real-time inputs are handled. In our game, we might handle them as follows (the aircraft methods are fictional to show the principle):

// One-time events
sf::Event event;
while (window.pollEvent(event))
{
    if (event.type == sf::Event::KeyPressed
     && event.key.code == sf::Keyboard::X)
        mPlayerAircraft->launchMissile();
}

// Real-time input
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
    mPlayerAircraft->moveLeft();
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
    mPlayerAircraft->moveRight();

There are several problems with this approach. On one side, we have hardcoded keys, so a user cannot choose WASD instead of arrow keys for movement. On the other side, we gather input and logic code in one place. The game logic code grows as we implement more features, and makes the originally simple code complicated.

For example, imagine that we want to keep the airplane inside...

Customizing key bindings


A big part with input management in a game is allowing the user to customize how he interacts with it, like the keys. Most of the time, you can find the most popular key bindings and see them written directly in the code. But there will always be people that want to do stuff their way.

We have to provide tools in order to dynamically bind the keys to specific actions. With the command queue introduced in the previous sections, this becomes a much easier task to accomplish.

With the command queue, we already define specific actions for a specific key. The difference is that right now, we have it hardcoded as follows:

if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
    commands.push(moveLeft);    
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
    commands.push(moveRight);

The problem with this code is that it is very inflexible. We have to change a lot in order to allow any key to respond to any action. We have two clearly separate sets of data that we want...

Summary


Reading through this chapter, you learned a whole new mechanism to handle input and deliver it correctly to the game's entities. It may not be the simplest concept you will come across, but it certainly pays off later, when you see it under heavier action. Not only have we played with event delivering systems, but we also paid a lot of attention on how to capture input and handle every detail about it. This is essential for every game, after all, who would like to play a game that plays itself?

After having a basic world scene with robust behaviors and features, it is now time to start looking at other phases of a game's development. In other words, the next chapter will cover mechanisms which are not directly related to the game's mechanics and systems, but that instead allow a coherent flow between multiple parts of a game, such as the pause and main menu, the game itself and others that you will encounter. Therefore, expect a lot of interesting information on handling this kind...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
SFML Game Development
Published in: Jun 2013Publisher: PacktISBN-13: 9781849696845
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Artur Moreira

Artur Moreira is a game development enthusiast who ultimately aims to start a new game development company in his home country. He has been programming games and game-related software for over 4 years. Most of the effort in that time was put in creating an open source game-making library with lots of flexibility and portability. The library is called Nephilim and is known for supporting all major desktop and mobile operating systems, making game development fully crossplatform and fast. Alongside this big project, he keeps making his own prototypes and games for educational and commercial purposes. Aside from the programming, he also puts some focus in creative areas such as 3D modeling, digital painting, and music composing.
Read more about Artur Moreira

author image
Henrik Vogelius Hansson

Henrik Vogelius Hansson has always been in love with both games and programming. He started his education fairly early and continued on into the indie scene with Defrost Games and their game Project Temporality. The next company that hired him was Paradox Development Studio where he got to work on titles such as Crusader Kings 2. Beside the game companies, Henrik has also been very active in the SFML community and has even provided a binding for Ruby called rbSFML.
Read more about Henrik Vogelius Hansson