Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Beginning C++ Game Programming. - Second Edition

You're reading from  Beginning C++ Game Programming. - Second Edition

Product type Book
Published in Oct 2019
Publisher Packt
ISBN-13 9781838648572
Pages 746 pages
Edition 2nd Edition
Languages
Author (1):
John Horton John Horton
Profile icon John Horton

Table of Contents (25) Chapters

Preface 1. Chapter 1: C++, SFML, Visual Studio, and Starting the First Game 2. Chapter 2: Variables, Operators, and Decisions – Animating Sprites 3. Chapter 3: C++ Strings and SFML Time – Player Input and HUD 4. Chapter 4: Loops, Arrays, Switches, Enumerations, and Functions – Implementing Game Mechanics 5. Chapter 5: Collisions, Sound, and End Conditions – Making the Game Playable 6. Chapter 6: Object-Oriented Programming – Starting the Pong Game 7. Chapter 7: Dynamic Collision Detection and Physics – Finishing the Pong Game 8. Chapter 8: SFML Views – Starting the Zombie Shooter Game 9. Chapter 9: C++ References, Sprite Sheets, and Vertex Arrays 10. Chapter 10: Pointers, the Standard Template Library, and Texture Management 11. Chapter 11: Collision Detection, Pickups, and Bullets 12. Chapter 12: Layering Views and Implementing the HUD 13. Chapter 13: Sound Effects, File I/O, and Finishing the Game 14. Chapter 14: Abstraction and Code Management – Making Better Use of OOP 15. Chapter 15: Advanced OOP – Inheritance and Polymorphism 16. Chapter 16: Building Playable Levels and Collision Detection 17. Chapter 17: Sound Spatialization and the HUD 18. Chapter 18: Particle Systems and Shaders 19. Chapter 19: Game Programming Design Patterns – Starting the Space Invaders ++ Game 20. Chapter 20: Game Objects and Components 21. Chapter 21: File I/O and the Game Object Factory 22. Chapter 22: Using Game Objects and Building a Game 23. Chapter 23: Before You Go... 24. Other Books You May Enjoy

Chapter 20: Game Objects and Components

In this chapter, we will be doing all the coding related to the Entity-Component pattern we discussed at the beginning of the previous chapter. This means we will code the base Component class, which all the other components will be derived from. We will also put our new knowledge of smart pointers to good use so that we don't have to concern ourselves with keeping track of the memory we allocate for these components. We will also code the GameObject class in this chapter.

We will cover the following topics in this chapter:

  • Preparing to code the components
  • Coding the Component base class
  • Coding the collider components
  • Coding the graphics components
  • Coding the update components
  • Coding the GameObject class

Let's discuss the components a bit more before we start coding. Please note that, in this chapter, I will try and reinforce how the Entity-Component system fits together and how all the components...

Preparing to code the components

As you work through this chapter, there will be lots of errors, and some of them won't seem logical. For example, you will get errors saying that a class doesn't exist when it is one of the classes you have already coded. The reason for this is that, when a class has an error in it, other classes can't reliably use it without getting errors as well. It is because of the interconnected nature of all the classes that we will not get rid of all the errors and have executable code again until near the end of the next chapter. It would have been possible to add code in smaller chunks to the various classes and the project would have been error-free more frequently. Doing things that gradually, however, would have meant constantly dipping in and out of classes. When you are building your own projects, this is sometimes a good way to do it, but I thought the most instructive thing to do for this project would be to help you get it built as quickly...

Coding the Component base class

Create a new header file in the Header Files/GameObjects filter called Component.h and add the following code:

#pragma once
#include "GameObjectSharer.h"
#include <string>
using namespace std;
class GameObject;
class Component {
public:
    virtual string getType() = 0;
    virtual string getSpecificType() = 0;
    virtual void disableComponent() = 0;
    virtual void enableComponent() = 0;
    virtual bool enabled() = 0;
    virtual void start(GameObjectSharer* gos, GameObject* self) = 0;
};

This is the base class of every component in every game object. The pure virtual functions mean that a component can never be instantiated and must always be inherited from first. Functions allow the type and specific type of a component to be accessed. Component types include collider, graphics, transform, and update, but...

Coding the collider components

The Space Invaders ++ game will only have one simple type of collider. It will be a rectangular box around the object, just like those we had in the Zombie Apocalypse and Pong games. However, it is easily conceivable that you might need other types of collider; perhaps a circle-shaped collider or a non-encompassing collider such as those we used for the head, feet, and sides of Thomas and Bob back in the Thomas Was Late game.

For this reason, there will be a base ColliderComponent class (that inherits from Component) which will handle the basic functionality of all the colliders, as well as RectColliderComponent, which will add the specific functionality of an all-encompassing rectangle-shaped collider. New collider types can then be added as required for the game being developed.

What follows is the base class to the specific collider, ColliderComponent.

Coding the ColliderComponent class

Create a new header file in the Header Files/GameObjects...

Coding the graphics components

The Space Invaders ++ game will only have one specific type of graphics component. It is called StandardGraphicsComponent. As with the collider components, we will implement a base GraphicsComponent class to make it easy to add other graphics-related components, should we wish. For example, in the classic arcade version of Space Invaders, the invaders flapped their arms up and down with two frames of animation. Once you see how StandardGraphicsComponent works, you will be able to easily code another class (perhaps AnimatedGraphicsComponent) that draws itself with a different Sprite instance every half a second or so. You could also have a graphics component that has a shader (perhaps ShaderGraphicsComponent) for fast and cool effects. There are more possibilities besides these.

Coding the GraphicsComponent class

Create a new header file in the Header Files/GameObjects filter called GraphicsComponent.h and add the following code:

#pragma once...

Coding the TransformComponent class

Create a new header file in the Header Files/GameObjects filter called TransformComponent.h and add the following code:

#pragma once
#include "Component.h"
#include<SFML/Graphics.hpp>
using namespace sf;
class Component;
class TransformComponent : public Component {
private:
    const string m_Type = "transform";
    Vector2f m_Location;
    float m_Height;
    float m_Width;
public:
    TransformComponent(
        float width, float height, Vector2f location);
    Vector2f& getLocation();
    Vector2f getSize();
    /****************************************************
    *****************************************************
    From Component interface
    ...

Coding update components

As you might expect by now, we will code an UpdateComponent class that will inherit from the Component class. It will have all the functionality that every UpdateComponent will need and then we will code classes derived from UpdateComponent. These will contain functionality specific to individual objects in the game. For this game, we will have BulletUpdateComponent, InvaderUpdateComponent, and PlayerUpdateComponent. When you work on your own project and you want an object in the game that behaves in a specific unique manner, just code a new update-based component for it and you'll be good-to-go. Update-based components define behavior.

Coding the UpdateComponent class

Create a new header file in the Header Files/GameObjects filter called UpdateComponent.h and add the following code:

#pragma once
#include "Component.h"
class UpdateComponent : public Component
{
private:
    string m_Type = "update";
 ...

Coding the GameObject class

I am going to go through the code in this class in quite a lot of detail because it is key to how all the other classes work. I think you will benefit, however, from seeing the code in its entirety and studying it first. With this in mind, create a new header file in the Header Files/GameObjects filter called GameObject.h and add the following code:

#pragma once
#include <SFML/Graphics.hpp>
#include <vector>
#include <string>
#include "Component.h"
#include "GraphicsComponent.h"
#include "GameObjectSharer.h"
#include "UpdateComponent.h"
class GameObject {
private:
    vector<shared_ptr<Component>> m_Components;
    string m_Tag;
    bool m_Active = false;
    int m_NumberUpdateComponents = 0;
    bool m_HasUpdateComponent = false;
    int m_FirstUpdateComponentLocation...

Summary

In this chapter, we have completed all the code that will draw our game objects to the screen, control their behavior, and let them interact with other classes through collisions. The most important thing to take away from this chapter is not how any of the specific component-based classes work but how flexible the Entity-Component system is. If you want a game object that behaves in a certain way, create a new update component. If it needs to know about other objects in the game, get a pointer to the appropriate component in the start function. If it needs to be drawn in a fancy manner, perhaps with a shader or an animation, code a graphics component that performs the actions in the draw function. If you need multiple colliders, like we did for Thomas and Bob in the Thomas Was Late project, this is no problem: code a new collider-based component.

In the next chapter, we will code the file input and output system, as well as the class that will be the factory that builds...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Beginning C++ Game Programming. - Second Edition
Published in: Oct 2019 Publisher: Packt ISBN-13: 9781838648572
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.
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}