Home Game Development SFML Game Development

SFML Game Development

By Artur Moreira , Henrik Vogelius Hansson , Jan Haller and 2 more
books-svg-icon Book
Subscription FREE
eBook + Subscription €11.99
eBook €28.99
Print + eBook €37.99
READ FOR FREE Free Trial for 7 days. €11.99 p/m after trial. Cancel Anytime! BUY NOW BUY NOW BUY NOW
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
READ FOR FREE Free Trial for 7 days. €11.99 p/m after trial. Cancel Anytime! BUY NOW BUY NOW BUY NOW
Subscription FREE
eBook + Subscription €11.99
eBook €28.99
Print + eBook €37.99
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
  1. Free Chapter
    Making a Game Tick
About this book
Game development comprises the combination of many different aspects such as game logics, graphics, audio, user input, physics and much more. SFML is an Open Source C++ library designed to make game development more accessible, exposing multimedia components to the user through a simple, yet powerful interface. If you are a C++ programmer with a stack of ideas in your head and seeking a platform for implementation, your search ends here.Starting with nothing more than a blank screen, SFML Game Development will provide you with all the guidance you need to create your first fully featured 2D game using SFML 2.0. By the end, you'll have learned the basic principles of game development, including advanced topics such as how to network your game, how to utilize particle systems and much more.SFML Game Development starts with an overview of windows, graphics, and user inputs. After this brief introduction, you will start to get to grips with SFML by building up a world of different game objects, and implementing more and more gameplay features. Eventually, you'll be handling advanced visual effects, audio effects and network programming like an old pro. New concepts are discussed, while the code steadily develops.SFML Game Development will get you started with animations, particle effects and shaders. As well as these fundamental game aspects, we're also covering network programming to the extent where you'll be able to support the game running from two different machines. The most important part, the gameplay implementation with enemies and missiles, will make up the core of our top-scrolling airplane shoot' em-up game!You will learn everything you need in SFML Game Development in order to start with game development and come closer to creating your own game.
Publication date:
June 2013
Publisher
Packt
Pages
296
ISBN
9781849696845

 

Chapter 1. Making a Game Tick

Through the words in this book, we will attempt to convey the best knowledge we possibly can. We aim to teach techniques that we learned along the years, techniques that we would like to have been told about in our early days of game development. We now write this book to save your time, by showing you directly the solution to common problems, and why things work the way they do.

Alongside our attempt to teach the basics and a little beyond game development, we will especially focus on the Simple and Fast Multimedia Library (SFML). Every part of this book will be about developing a game and leveraging the advantages that SFML is able to provide us. To spice things up a little, and since we use the C++ programming language, we will try our best to use the language in a modern way, applying more recent language features, techniques, and programming styles, in a fully object-oriented approach. C++ is a great tool and it always has been, however, it is a good thing if we grow with it and adapt to the possibilities it has to offer in the present day.

This chapter introduces the SFML library and shows you its capabilities by creating a small application. We are going to address the basic concepts relevant to game development, namely; rendering, game loops, and code organization. Furthermore, the first part of our game code developed, will serve as a basis for the coming chapters.

 

Introducing SFML


Before we start developing a game, we would like to tell you a little bit about the library we will use throughout the book. SFML is an object-oriented C++ framework. As can be guessed by the name, its philosophy consists of having a simple, user-friendly application programming interface (API), and allowing for both high performances and fast development.

SFML is a multimedia library, meaning that it provides a layer between you and the hardware. It is split into five modules:

  • System: This is a core module upon which all other modules are built. It provides two-dimensional and three-dimensional vector classes, clocks, threads, and Unicode strings, among other things.

  • Window: The Window module makes it possible to create application windows, and to collect user input, such as mouse movement or key presses.

  • Graphics: This module provides all functionalities that are related to two-dimensional rendering, such as images, texts, shapes, and colors.

  • Audio: SFML also offers a module to work with sound. When you want to load a music theme and play it on the computer's loudspeakers, this is the module you have to look for.

  • Network: Another medium SFML covers is the network, a more and more important part of our interconnected world. This module allows you to send data over LAN or the Internet; it also lets you work with protocols, such as HTTP or FTP.

If you don't need all the modules, it is possible to use only a part of SFML. We will cover every module in SFML, but of course we are not able to use every single class. We recommend having a look at the SFML documentation, which is available at www.sfml-dev.org/documentation.php. The documentation explains every class and function in a detailed manner, and is an invaluable tool when developing a game using SFML.

SFML is open source, which means that you have access to its complete source code. Usually, the implementations aren't relevant to the user, but if you are interested in how something was solved, don't hesitate to skim through SFML's code.

The library uses the zlib/libpng license, which is extremely permissive. You can use SFML in both open and closed source projects, both free and commercial.

Downloading and installation

There are two possibilities when using SFML: download the pre-built libraries, or recompile them yourself. The first option is simpler, but you have to wait for major versions (2.0, 2.1, and so on) to be released. If you want to use the latest development sources, you can download the current Git revision. The configuration software CMake is used to prepare the sources for compilation with a compiler of your choice. For example, CMake creates Visual Studio solutions or g++ Makefiles. The recompilation process is explained in detail in the SFML tutorials, which can be found at www.sfml-dev.org/tutorials.php.

As mentioned, SFML is split into five modules. There are five headers to include a complete module (and its dependencies). To include the whole Audio module, you can write:

#include <SFML/Audio.hpp>

On the other hand, if you need a specific header file, you can find it in the directory of the corresponding module:

#include <SFML/Audio/Sound.hpp>

Each module is compiled to a separate library, which makes it possible to use only the modules you need. SFML can be built for release or debug mode, and it can be linked statically or dynamically. The resulting libraries are named according to the scheme sfml-module[-s][-d]. The -s postfix is required if you link statically; the -d postfix specifies debug mode. For example, to link the Graphics module statically in release mode, you have to specify the library sfml-graphics-s in your linker options. Depending on your compiler, a file extension (such as .lib) might be necessary. Keep in mind that some modules depend on others; therefore, you have to link the dependencies too. For example, Graphics depends on Window, which depends on System; therefore, you should link the three (in this order).

An important point to note is that if you link SFML statically, you have to define the macro SFML_STATIC in your projects, so that the linker knows what functions to resolve.

In case you do not know how linking a library works for a specific compiler, please refer to the online tutorials. They explain how to install everything correctly, and are always up-to-date.

A minimal example

Before you go deeper into the book and SFML itself, let's take a look at a minimal application example to show how an application that uses this library looks like, its general flow of execution, and some basic functionality.

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(640, 480), "SFML Application");
    sf::CircleShape shape;
    shape.setRadius(40.f);
    shape.setPosition(100.f, 100.f);
    shape.setFillColor(sf::Color::Cyan);
    while (window.isOpen())
    {
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
    }
    window.clear();
    window.draw(shape);
    window.display();
    }
}

All this application does is to open a window onto which we can render, with a width of 640 pixels and a height of 480 pixels. Its title says "SFML Application". Then, a cyan geometric circle is created, and while the window is open, it is drawn to the screen. Finally, for each time the circle is drawn, the program checks for user input that may have arrived from the underlying window. In our case, we only handle the sf::Event::Closed event, which arrives every time the application is requested to terminate, such as when we click on the close button, or press an application-terminating shortcut, such as Alt + F4.

If you failed to understand a part of or the whole snippet of code, don't fear. This book contains all you need to know about this and much more.

 

A few notes on C++


C++ is a very powerful, but also very complex programming language; even after years one never stops learning. We expect you to understand the basic language features (variables, data types, functions, classes, polymorphism, pointers, and templates), as well as the most important parts of the standard library (strings, streams, and the STL). If you feel unsure, we recommend reading a good C++ book, before or in parallel to this book, since SFML and our code sometimes uses advanced techniques. Game development is a difficult topic on its own; it is very frustrating if you additionally have to fight C++. Even if it takes some time to reasonably learn the programming language, it is a good investment, since it will save you days of tedious debugging.

You may have heard that in 2011, a new C++ standard was released, which introduced a lot of extremely useful features. We are going to use a few C++11 features in the book, and show how they can improve code. Each time we use a new C++11 technique, we will briefly explain it.

An issue that is widely underestimated, especially by beginners, is the importance of clean code. Before making a game, it is always a good idea to have a rough imagination of the game features and their implementation. It may help to draw sketches on a paper, in order to visualize contexts better. Also during development, it is crucial to keep an eye on the code design, and to refactor messy code where necessary.

Some key aspects of good code are as follows:

  • Modularity: In this the functionalities are separated, and dependencies between them are reduced to a minimum. This allows you to maintain and debug application parts locally, as well as, to change the implementation of a module without affecting the other modules. Concretely, we achieve this by widely avoiding global variables, distributing functionality to different classes, and keeping interfaces between them small. We also split the code base to different headers and implementation files, and try to include only what is really necessary.

  • Abstraction: In this, the functionality is encapsulated into classes and functions. Code duplication is avoided. The usage of low-level operations, such as manual memory management (new/delete) is minimized, because it is inherently error-prone, and replaced with idioms such as RAII. In short, keep most of your code on a high abstraction level, such that it is expressive and achieves a lot of actions within a few lines. When you need boilerplate code, wrap it into functions, so that the code using it still looks clean.

  • Code style: One thing, be consistent. It does not matter what naming convention you use, or if you have a space between if and the opening parenthesis, so long as you stick to one style. It is important that you keep the code readable and expressive, so that you still recognize what you have done after several weeks. Use comments where appropriate.

After this initial sermon, we hope that you have recognized how a well-structured code can keep up your motivation to develop, while on the other hand, a total mess is contra-productive and frustrating, when it comes to maintenance, debugging, or integration of new features. Don't be afraid if this advice sounds very abstract; you will automatically gain experience while developing projects.

By the way, the code we are going to develop during the chapters is available for download on the Packt Publishing website.

       
About the Authors
  • 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.

    Browse publications by this author
  • 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.

    Browse publications by this author
  • Jan Haller

    contacted on 9 may '16

    Browse publications by this author
  • Henrik Valter Vogelius

    contacted on 9 may '16

    Browse publications by this author
  • SFML
Latest Reviews (12 reviews total)
A dated book with a substantial amount of great information.
The book is concise, understandable and to the point about game development using SFML.
Easy to understand, comes with source code files.
SFML Game Development
Unlock this book and the full library FREE for 7 days
Start now