Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Mastering SFML Game Development
Mastering SFML Game Development

Mastering SFML Game Development: Inject new life and light into your old SFML projects by advancing to the next level.

eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Mastering SFML Game Development

Chapter 2.  Its Game Time! - Designing the Project

In the previous chapter, we covered the essential parts of our pre-established code base that is going to be used while creating a game. The time has come to take what we have learned and build upon it, by focusing on project-specific code that will be unique to the game we are making.

In this chapter, we are going to be covering the following topics:

  • Implementing key entity components and systems for minimal gameplay
  • Creating a couple of states for navigating the game
  • Arranging all of our code into a cohesive, working project

We have a whole game to design, so let us get to it!

Use of copyrighted resources

In this chapter, and for the entire length of this book, we are going to be using these resources:

Entity placement and rendering

Let us start with the basics. Most (if not all) entities in any game we build are going to be positioned within the world. Let us ignore the corner cases of special types of entities for now. In order to represent the entity position, we are going to be creating a position component like so:

class C_Position : public C_Base{ 
public: 
  C_Position(): C_Base(Component::Position), m_elevation(0){} 
 
  void ReadIn(std::stringstream& l_stream){ 
    l_stream >> m_position.x >> m_position.y >> m_elevation; 
  } 
 
  sf::Vector2f GetPosition() const { ... } 
  sf::Vector2f GetOldPosition() const { ... } 
  unsigned int GetElevation() const { ... } 
  void SetPosition(float l_x, float l_y){ ... } 
  void SetPosition(const sf::Vector2f& l_vec){ ... } 
  void SetElevation(unsigned int l_elevation){ ... } 
  void MoveBy(float l_x, float l_y){ ... } 
  void MoveBy(const sf::Vector2f& l_vec){ ... } 
private: 
  sf::Vector2f m_position; 
...

Entity kinematics

The code we have written so far would only produce a static, unmoving scene. Since that isn't very exciting, let's work on adding potential for entity movement. Since it calls for more data being stored, we need another component type to work with:

class C_Movable : public C_Base{ 
public: 
  C_Movable() : C_Base(Component::Movable), 
    m_velocityMax(0.f), m_direction((Direction)0){} 
 
  void ReadIn(std::stringstream& l_stream){ 
    l_stream >> m_velocityMax >> m_speed.x >> m_speed.y; 
    unsigned int dir = 0; 
    l_stream >> dir; 
    m_direction = static_cast<Direction>(dir); 
  } 
  ... 
  void SetVelocity(const sf::Vector2f& l_vec){ ... } 
  void SetMaxVelocity(float l_vel){ ... } 
  void SetSpeed(const sf::Vector2f& l_vec){ ... } 
  void SetAcceleration(const sf::Vector2f& l_vec){ ... } 
  void SetDirection(const Direction& l_dir){ ... } 
  void AddVelocity(const sf::Vector2f& l_vec){ ... } 
  void...

Handling collisions

In order to make the game we're making feel like more than just entities moving across a static background with no consequences, collisions have to be checked for and handled. Within the ECS paradigm, this can be achieved by implementing a collidable component. For more flexibility, let's define multiple points that the collision box can be attached to:

enum class Origin{ Top_Left, Abs_Centre, Mid_Bottom }; 

The TOP_LEFT origin simply places the collision rectangle's top-left corner to the position provided. ABS_CENTRE moves that rectangle's centre to the position, and the MIDDLE_BOTTOM origin places it halfway through the x axis and all the way down the y axis. Consider the following illustration:

Handling collisions

With this information, let us work on implementing the collidable component:

class C_Collidable : public C_Base{ 
public: 
  C_Collidable(): C_Base(Component::Collidable),  
    m_origin(Origin::Mid_Bottom), m_collidingOnX(false), 
    m_collidingOnY(false...

Use of copyrighted resources


In this chapter, and for the entire length of this book, we are going to be using these resources:

Entity placement and rendering


Let us start with the basics. Most (if not all) entities in any game we build are going to be positioned within the world. Let us ignore the corner cases of special types of entities for now. In order to represent the entity position, we are going to be creating a position component like so:

class C_Position : public C_Base{ 
public: 
  C_Position(): C_Base(Component::Position), m_elevation(0){} 
 
  void ReadIn(std::stringstream& l_stream){ 
    l_stream >> m_position.x >> m_position.y >> m_elevation; 
  } 
 
  sf::Vector2f GetPosition() const { ... } 
  sf::Vector2f GetOldPosition() const { ... } 
  unsigned int GetElevation() const { ... } 
  void SetPosition(float l_x, float l_y){ ... } 
  void SetPosition(const sf::Vector2f& l_vec){ ... } 
  void SetElevation(unsigned int l_elevation){ ... } 
  void MoveBy(float l_x, float l_y){ ... } 
  void MoveBy(const sf::Vector2f& l_vec){ ... } 
private: 
  sf::Vector2f m_position; 
 ...

Entity kinematics


The code we have written so far would only produce a static, unmoving scene. Since that isn't very exciting, let's work on adding potential for entity movement. Since it calls for more data being stored, we need another component type to work with:

class C_Movable : public C_Base{ 
public: 
  C_Movable() : C_Base(Component::Movable), 
    m_velocityMax(0.f), m_direction((Direction)0){} 
 
  void ReadIn(std::stringstream& l_stream){ 
    l_stream >> m_velocityMax >> m_speed.x >> m_speed.y; 
    unsigned int dir = 0; 
    l_stream >> dir; 
    m_direction = static_cast<Direction>(dir); 
  } 
  ... 
  void SetVelocity(const sf::Vector2f& l_vec){ ... } 
  void SetMaxVelocity(float l_vel){ ... } 
  void SetSpeed(const sf::Vector2f& l_vec){ ... } 
  void SetAcceleration(const sf::Vector2f& l_vec){ ... } 
  void SetDirection(const Direction& l_dir){ ... } 
  void AddVelocity(const sf::Vector2f& l_vec){ ... } 
  void ApplyFriction...

Handling collisions


In order to make the game we're making feel like more than just entities moving across a static background with no consequences, collisions have to be checked for and handled. Within the ECS paradigm, this can be achieved by implementing a collidable component. For more flexibility, let's define multiple points that the collision box can be attached to:

enum class Origin{ Top_Left, Abs_Centre, Mid_Bottom }; 

The TOP_LEFT origin simply places the collision rectangle's top-left corner to the position provided. ABS_CENTRE moves that rectangle's centre to the position, and the MIDDLE_BOTTOM origin places it halfway through the x axis and all the way down the y axis. Consider the following illustration:

With this information, let us work on implementing the collidable component:

class C_Collidable : public C_Base{ 
public: 
  C_Collidable(): C_Base(Component::Collidable),  
    m_origin(Origin::Mid_Bottom), m_collidingOnX(false), 
    m_collidingOnY(false){} 
 
  void ReadIn...

Controlling entities


Since we have already laid down the code foundation, it's now possible to focus on controlling the entities on the screen. Whether they're being controlled as player avatars by means of a keyboard, or through some sort of artificial intelligence (AI), they still need to have this basic component:

class C_Controller : public C_Base{ 
public: 
  C_Controller() : C_Base(Component::Controller){} 
  void ReadIn(std::stringstream& l_stream){} 
}; 

As you can tell, we have absolutely no data that gets stored here so far. For now, it can simply be considered just a specific signature that lets the ECS know it can be controlled.

Control system

In order for entities to be controlled, they must have three basic component types:

S_Control::S_Control(SystemManager* l_systemMgr) 
  : S_Base(System::Control,l_systemMgr) 
{ 
  Bitmask req; 
  req.TurnOnBit((unsigned int)Component::Position); 
  req.TurnOnBit((unsigned int)Component::Movable); 
  req.TurnOnBit((unsigned int)Component...

Entity states


Having entities that are able to move around now implies they can either be standing still or moving. This quickly brings about the issue of entity states. Luckily, we have an elegant way of dealing with that, by introducing another component type and a system. Let's start by enumerating all possible entity states, and using the enumeration to establish a component type:

enum class EntityState{ Idle, Walking, Attacking, Hurt, Dying }; 
 
class C_State : public C_Base{ 
public: 
  C_State(): C_Base(Component::State){} 
  void ReadIn(std::stringstream& l_stream){ 
    unsigned int state = 0; 
    l_stream >> state; 
    m_state = static_cast<EntityState>(state); 
  } 
 
  EntityState GetState() const { ... } 
  void SetState(const EntityState& l_state){ ... } 
private: 
  EntityState m_state; 
}; 

That's all we have to keep track of inside the component class. Time to move on to the system!

State system

Because state is not directly tethered to any other data...

Sheet animation system


One of the objects sensitive to state changes is the sprite sheet animation system. Knowing an entity's state is of paramount importance, if we desire to apply animations that describe its current action:

S_SheetAnimation::S_SheetAnimation(SystemManager* l_systemMgr) 
  : S_Base(System::SheetAnimation,l_systemMgr) 
{ 
  Bitmask req; 
  req.TurnOnBit((unsigned int)Component::SpriteSheet); 
  req.TurnOnBit((unsigned int)Component::State); 
  m_requiredComponents.push_back(req); 
 
  m_systemManager->GetMessageHandler()-> 
    Subscribe(EntityMessage::State_Changed,this); 
} 

As you can see, all we need are two component types and a subscription to a message type of State_Changed. So far, so good!

Updating the sprite sheets can get a little involved, so let us delve right into it:

void S_SheetAnimation::Update(float l_dT){ 
  EntityManager* entities = m_systemManager->GetEntityManager(); 
  for(auto &entity : m_entities){ 
    auto sheet = entities-> 
  ...

Entity sounds


Just like states, an entity can emit multiple different types of sound. Each different type must also have certain parameters associated with it:

enum class EntitySound{ None = -1, Footstep, Attack, 
  Hurt, Death, COUNT }; 
 
struct SoundParameters{ 
  static const int Max_SoundFrames = 5; 
  SoundParameters(){ 
    for (int i = 0; i < Max_SoundFrames; ++i){ m_frames[i] = -1; } 
  } 
  std::string m_sound; 
  std::array<int, Max_SoundFrames> m_frames; 
}; 

struct SoundParameters simply stores the name of the sound, as well as an array of integers for the maximum number of sound frames. A sound frame is the glue between sounds and sprite sheets, as it defines during which animation frames the sound is emitted.

  • Having defined the previous data structure allows us to successfully create a sound emitter component type:

class C_SoundEmitter : public C_Base{ 
public: 
  C_SoundEmitter():C_Base(Component::SoundEmitter),m_soundID(-1){} 
  void ReadIn(std::stringstream& l_stream...

Implementing the menu state


With most of the backend already covered, we're ready to move towards the front, and start working on more interactive aspects of the project, such as interfaces. Let's start by creating a main menu:

void State_MainMenu::OnCreate(){ 
  auto context = m_stateMgr->GetContext(); 
  GUI_Manager* gui = context->m_guiManager; 
  gui->LoadInterface("MainMenu.interface", "MainMenu"); 
  gui->GetInterface("MainMenu")->SetPosition( 
    sf::Vector2f(250.f, 168.f)); 
  EventManager* eMgr = context->m_eventManager; 
  eMgr->AddCallback("MainMenu_Play", &State_MainMenu::Play, this); 
  eMgr->AddCallback("MainMenu_Quit", &State_MainMenu::Quit, this); 
} 

All of these classes have already been covered in Chapter 1 , Under the Hood - Setting up the Backend, but let us have a quick rundown of what this does once more. After we obtain the shared context, a main menu interface is loaded and positioned on screen. The m_eventManager is then used to bind...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Build custom tools, designed to work with your specific game.
  • Use raw modern OpenGL and go beyond SFML.
  • Revamp your code for better structural design, faster rendering, and flashier graphics.
  • Use advanced lighting techniques to add that extra touch of sophistication.
  • Implement a very fast and efficient particle system by using a cache-friendly design.

Description

SFML is a cross-platform software development library written in C++ with bindings available for many programming languages. It provides a simple interface to the various components of your PC, to ease the development of games and multimedia applications. This book will help you become an expert of SFML by using all of its features to its full potential. It begins by going over some of the foundational code necessary in order to make our RPG project run. By the end of chapter 3, we will have successfully picked up and deployed a fast and efficient particle system that makes the game look much more ‘alive’. Throughout the next couple of chapters, you will be successfully editing the game maps with ease, all thanks to the custom tools we’re going to be building. From this point on, it’s all about making the game look good. After being introduced to the use of shaders and raw OpenGL, you will be guided through implementing dynamic scene lighting, the use of normal and specular maps, and dynamic soft shadows. However, no project is complete without being optimized first. The very last chapter will wrap up our project by making it lightning fast and efficient.

Who is this book for?

This book is ideal for game developers who have some basic knowledge of SFML and also are familiar with C++ coding in general. No knowledge of OpenGL or even more advanced rendering techniques is required. You will be guided through every bit of code step by step.

What you will learn

  • Dive deep into creating complex and visually stunning games using SFML, as well as advanced OpenGL rendering and shading techniques
  • Build an advanced, dynamic lighting and shadowing system to add an extra graphical kick to your games and make them feel a lot more dynamic
  • Craft your own custom tools for editing game media, such as maps, and speed up the process of content creation
  • Optimize your code to make it blazing fast and robust for the users, even with visually demanding scenes
  • Get a complete grip on the best practices and industry grade game development design patterns used for AAA projects

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 30, 2017
Length: 442 pages
Edition : 1st
Language : English
ISBN-13 : 9781786466846
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jan 30, 2017
Length: 442 pages
Edition : 1st
Language : English
ISBN-13 : 9781786466846
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 147.97
SFML Blueprints
$43.99
SFML Game Development By Example
$54.99
Mastering SFML Game Development
$48.99
Total $ 147.97 Stars icon

Table of Contents

10 Chapters
1. Under the Hood - Setting up the Backend Chevron down icon Chevron up icon
2. Its Game Time! - Designing the Project Chevron down icon Chevron up icon
3. Make It Rain! - Building a Particle System Chevron down icon Chevron up icon
4. Have Thy Gear Ready - Building Game Tools Chevron down icon Chevron up icon
5. Filling the Tool Belt - a few More Gadgets Chevron down icon Chevron up icon
6. Adding Some Finishing Touches - Using Shaders Chevron down icon Chevron up icon
7. One Step Forward, One Level Down - OpenGL Basics Chevron down icon Chevron up icon
8. Let There Be Light - An Introduction to Advanced Lighting Chevron down icon Chevron up icon
9. The Speed of Dark - Lighting and Shadows Chevron down icon Chevron up icon
10. A Chapter You Shouldnt Skip - Final Optimizations Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
Kamal johnson Dec 06, 2017
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
the price on the book is only 599Rs but the price on amazon is 1079Rsthe quality of the book is also very low.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.