Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
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
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
:

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781786469885
Languages :
Tools :
:

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 111.97
Mastering SFML Game Development
€36.99
SFML Game Development By Example
€41.99
SFML Blueprints
€32.99
Total 111.97 Stars icon
Banner background image

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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.