Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

Beginning C++ Game Programming: Learn C++ from scratch by building fun games
Beginning C++ Game Programming: Learn C++ from scratch by building fun games
Beginning C++ Game Programming: Learn C++ from scratch by building fun games
Ebook1,693 pages8 hours

Beginning C++ Game Programming: Learn C++ from scratch by building fun games

Rating: 3 out of 5 stars

3/5

()

Read preview
LanguageEnglish
PublisherPackt Publishing
Release dateMay 31, 2024
ISBN9781835088258
Beginning C++ Game Programming: Learn C++ from scratch by building fun games
Author

John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.

Read more from John Horton

Related to Beginning C++ Game Programming

Related ebooks

Programming For You

View More

Reviews for Beginning C++ Game Programming

Rating: 3 out of 5 stars
3/5

1 rating0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Beginning C++ Game Programming - John Horton

    9781835081747.png

    Beginning C++ Game Programming

    Third Edition

    Learn C++ from scratch by building fun games

    John Horton

    Beginning C++ Game Programming

    Third Edition

    Copyright © 2024 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    Senior Publishing Product Manager: Larissa Pinto

    Acquisition Editor – Peer Reviews: Jane Dsouza

    Project Editor: Meenakshi Vijay

    Content Development Editor: Shikha Parashar

    Copy Editor: Safis Editing

    Technical Editor: Simanta Rajbangshi

    Proofreader: Safis Editing

    Indexer: Hemangini Bari

    Presentation Designer: Rajesh Shirsath

    Developer Relations Marketing Executive: Sohini Ghosh

    First published: October 2016

    Second edition: October 2019

    Third edition: May 2024

    Production reference: 1240524

    Published by Packt Publishing Ltd.

    Grosvenor House

    11 St Paul’s Square

    Birmingham

    B3 1RB, UK.

    ISBN 978-1-83508-174-7

    www.packt.com

    Contributors

    About the author

    John Horton is a programming and gaming enthusiast based in the UK.

    Dedicated to two brothers, Ray and Barry, for your guidance, example, and support.

    About the reviewer

    Yoan Rock is a 26-year-old developer with over 4 years of experience in the gaming industry. With a background in C++ software engineering, Yoan’s expertise lies in C++ programming within the gaming industry, particularly in utilizing Unreal Engine and sometimes Blueprints to create immersive experiences.

    During his tenure at Limbic Studio, Yoan contributed significantly to the development of Park Beyond, an AAA-released game where players create and manage their own theme park. He excelled in gameplay development, bug fixing, and fostering effective communication among team members.

    Yoan later collaborated with Chillchat on Primorden, a multiplayer project using Unreal Engine 5 and the Game play Ability system, where he played a key role in implementing game mechanics, monster abilities, and AI behavior trees.

    At Game Atelier, Yoan led UI development for an unannounced project, showcasing his proficiency in crafting immersive user experiences using Unreal Engine 5.3, Common UI, and, of course, UMG.

    Currently, Yoan is part of an exciting project with Blacksheep, contributing to an ambitious, unannounced venture. Always eager to innovate, Yoan stays updated with industry trends and is exploring Unreal Engine 5.3 for personal projects.

    Contents

    Preface

    Who this book is for

    What this book covers

    To get the most out of this book

    Get in touch

    Welcome to Beginning C++ Game Programming Third Edition!

    The games we will build

    Timber!!!

    Pong

    Zombie Arena

    Platform game

    Why you should learn game programming using C++ in 2024

    SFML

    Microsoft Visual Studio

    What about Mac and Linux?

    Installing Visual Studio 2022

    Setting up SFML

    Creating a new project in Visual Studio 2022

    Configuring the project properties

    Planning Timber!!!

    The project assets

    Making your own sound FX

    Adding the assets to the project

    Exploring the assets

    Understanding screen and internal coordinates

    Getting started with coding the game

    Making code clearer with comments

    The main function

    Presentation and syntax

    Returning values from a function

    Running the game

    Opening a window using SFML

    Including SFML features

    OOP, classes, and objects

    Using namespace sf

    SFML VideoMode and RenderWindow

    Running the game

    The game loop

    while loops

    C-style code comments

    Input, update, draw, repeat

    Detecting a key press

    Clearing and drawing the scene

    Running the game

    Drawing the game’s background

    Preparing the sprite using a texture

    Double buffering the background sprite

    Running the game

    Handling errors

    Configuration errors

    Compile errors

    Link errors

    Bugs

    Summary

    Frequently asked questions

    Variables, Operators, and Decisions: Animating Sprites

    Learning all about C++ variables

    Types of variables

    User-defined types

    Declaring and initializing variables

    Declaring variables

    Initializing variables

    Declaring and initializing in one step

    Constants

    Uniform initialization

    Declaring and initializing user-defined types

    Seeing how to manipulate the variables

    C++ arithmetic and assignment operators

    Getting things done with expressions

    Assignment

    Increment and decrement

    Adding clouds, a buzzing bee, and a tree

    Preparing the tree

    Preparing the bee

    Preparing the clouds

    Drawing the tree, the bee, and the clouds

    Random numbers

    Generating random numbers in C++

    Making decisions with if and else

    Logical operators

    C++ if and else

    If they come over the bridge, shoot them!

    Else do this instead

    Reader challenge

    Timing

    The frame rate problem

    The SFML frame rate solution

    Moving the clouds and the bee

    Giving life to the bee

    Blowing the clouds

    Summary

    Frequently Asked Questions

    C++ Strings, SFML Time: Player Input and HUD

    Pausing and restarting the game

    C++ strings

    Declaring strings

    Assigning a value to strings

    String Concatenation

    Getting the string length

    Manipulating strings another way with StringStream

    SFML Text and SFML Font

    Adding a score and a message

    Adding a time-bar

    Summary

    Frequently asked questions

    Loops, Arrays, Switch, Enumerations, and Functions: Implementing Game Mechanics

    Loops

    while loops

    Breaking out of a loop

    for loops

    Arrays

    Declaring an array

    Initializing the elements of an array

    Quickly initializing the elements of an array

    What do these arrays really do for our games?

    Making decisions with switch

    Class enumerations

    Getting started with functions

    Who designed all this weird and frustrating syntax and why is it the way it is?

    Function return types

    Function names

    Function parameters

    The function body

    Function prototypes

    Organizing functions

    Function scope

    A final word on functions – for now

    Growing the branches

    Preparing the branches

    Updating the branch sprites in each frame

    Drawing the branches

    Moving the branches

    Summary

    Frequently asked questions

    Collisions, Sound, and End Conditions: Making the Game Playable

    Preparing the player (and other sprites)

    Drawing the player and other sprites

    Handling the player’s input

    Handling setting up a new game

    Detecting the player chopping

    Detecting a key being released

    Animating the chopped logs and the axe

    Handling death

    Simple sound effects

    How SFML sound works

    When to play the sounds

    Adding the sound code

    Improving the game and code

    Summary

    Frequently asked questions

    Object-Oriented Programming – Starting the Pong Game

    Object-oriented programming

    Encapsulation

    Polymorphism

    Inheritance

    Why use OOP?

    What exactly is a class?

    The theory of a Pong bat

    Declaring the class, variables, and functions

    The class function definitions

    Using an instance of a class

    Creating the Pong project

    Coding the Bat class

    Coding Bat.h

    Constructor functions

    Continuing with the Bat.h explanation

    Coding Bat.cpp

    Using the Bat class and coding the main function

    Summary

    Frequently asked questions

    AABB Collision Detection and Physics – Finishing the Pong Game

    Coding the Ball class

    Using the Ball class

    Collision detection and scoring

    Running the game

    Learning about the C++ spaceship operator

    Summary

    Frequently asked questions

    SFML Views – Starting the Zombie Shooter Game

    Planning and starting the Zombie Arena game

    Creating a new project

    The project assets

    Exploring the assets

    Adding the assets to the project

    OOP and the Zombie Arena project

    Building the player – the first class

    Coding the Player class header file

    Coding the Player class function definitions

    Controlling the game camera with SFML View

    Starting the Zombie Arena game engine

    Managing the code files

    Starting to code the main game loop

    Summary

    Frequently asked questions

    C++ References, Sprite Sheets, and Vertex Arrays

    Understanding C++ references

    Summarizing references

    SFML vertex arrays and sprite sheets

    What is a sprite sheet?

    What is a vertex array?

    Building a background from tiles

    Building a vertex array

    Using the vertex array to draw

    Creating a randomly generated scrolling background

    Using the background

    Summary

    Frequently asked questions

    Pointers, the Standard Template Library, and Texture Management

    Learning about pointers

    Pointer syntax

    Declaring a pointer

    Initializing a pointer

    Reinitializing pointers

    Dereferencing a pointer

    Pointers are versatile and powerful

    Dynamically allocated memory

    Passing a pointer to a function

    Declaring and using a pointer to an object

    Pointers and arrays

    Summary of pointers

    Learning about the Standard Template Library

    What is a vector?

    Declaring a vector

    Adding data to a vector

    Accessing data in a vector

    Removing data from a vector

    Checking the size of a vector

    Looping/iterating through the elements of a vector

    What is a map?

    Declaring a map

    Adding data to a map

    Finding data in a map

    Removing data from a map

    Checking the size of a map

    Checking for keys in a map

    Looping/iterating through the key-value pairs of a map

    The auto keyword

    STL summary

    Summary

    Frequently asked questions

    Coding the TextureHolder Class and Building a Horde of Zombies

    Implementing the TextureHolder class

    Coding the TextureHolder header file

    Coding the TextureHolder function definitions

    What have we achieved with TextureHolder?

    Building a horde of zombies

    Coding the Zombie.h file

    Coding the Zombie.cpp file

    Using the Zombie class to create a horde

    Bringing the horde to life (or back to life)

    Using the TextureHolder class for all textures

    Changing the way the background gets its textures

    Changing the way the Player class gets its texture

    Summary

    Frequently asked questions

    Collision Detection, Pickups, and Bullets

    Coding the Bullet class

    Coding the Bullet header file

    Coding the Bullet source file

    Coding the shoot function

    Calculating the gradient in the shoot function

    Making the gradient positive in the shoot function

    Calculating the ratio between X and Y in the shoot function

    Finishing the shoot function explanation

    More bullet functions

    The Bullet class’s update function

    Making the bullets fly

    Including the Bullet class

    Control variables and the bullet array

    Reloading the gun

    Shooting a bullet

    Updating the bullets in each frame

    Drawing the bullets in each frame

    Giving the player a crosshair

    Coding a class for pickups

    Coding the Pickup header file

    Coding the Pickup class function definitions

    Using the Pickup class

    Detecting collisions

    Has a zombie been shot?

    Has the player been touched by a zombie?

    Has the player touched a pickup?

    Summary

    Frequently asked questions

    Layering Views and Implementing the HUD

    Adding all the Text and HUD objects

    Updating the HUD

    Drawing the HUD, home, and level-up screens

    Summary

    Sound Effects, File I/O, and Finishing the Game

    Saving and loading the high score

    Preparing sound effects

    Allowing the player to level up and spawning a new wave

    Restarting the game

    Playing the rest of the sounds

    Adding sound effects while the player is reloading

    Making a shooting sound

    Playing a sound when the player is hit

    Playing a sound when getting a pickup

    Making a splat sound when a zombie is shot

    Summary

    Frequently asked questions

    Run!

    About the game

    Creating the project

    Coding the main function

    Handling input

    Coding the Factory class

    Advanced OOP: inheritance and polymorphism

    Inheritance

    Extending a class

    Polymorphism

    Abstract classes: virtual and pure virtual functions

    Design patterns

    Entity Component System pattern

    Why lots of diverse object types are hard to manage

    Using a generic GameObject for better code structure

    Prefer composition over inheritance

    Factory pattern

    C++ smart pointers

    Shared pointers

    Unique pointers

    Casting smart pointers

    Coding the GameObject class

    Coding the Component class

    Coding the Graphics class

    Coding the Update class

    Running the code

    What next?

    Summary

    Sound, Game Logic, Inter-Object Communication, and the Player

    Coding the SoundEngine class

    Code the Game logic

    Coding the LevelUpdate class

    Coding the player: Part 1

    Coding the PlayerUpdate class

    Coding the PlayerGraphics class

    Coding the factory to use all our new classes

    Remembering the texture coordinates

    Running the game

    Summary

    Graphics, Cameras, Action

    Cameras, draw calls, and SFML View

    Coding the camera classes

    Coding the CameraUpdate class

    Coding the CameraGraphics class part 1

    The SFML View class

    Coding the CameraGraphics class part 2

    Adding camera instances to the game

    Running the game

    Summary

    Coding the Platforms, Player Animations, and Controls

    Coding the platforms

    Coding the PlatformUpdate class

    Coding the update function for the PlatformUpdate class

    Coding the PlatformGraphics class

    Building some platforms in the factory

    Running the game

    Adding functionality to the player

    Coding the player controls

    Running the game

    Coding the Animator class

    Coding the player animations

    Running the game

    Summary

    Building the Menu and Making It Rain

    Building an interactive menu

    Coding the MenuUpdate class

    Coding the MenuGraphics class

    Building a menu in the factory

    Running the game

    Making it rain

    Coding the RainGraphics class

    Making it rain in the factory

    Running the game

    Summary

    Fireballs and Spatialization

    What is spatialization?

    Emitters, attenuation, and listeners

    Handling spatialization using SFML

    Upgrading the SoundEngine class

    Fireballs

    Coding the FireballUpdate class

    Coding the FireballGraphics class

    Coding FireballGraphics.h

    Coding FireballGraphics.cpp

    Building some fireballs in the factory

    Running the code

    Summary

    Parallax Backgrounds and Shaders

    Learning about OpenGL, shaders, and GLSL

    The programmable pipeline and shaders

    Coding a hypothetical fragment shader

    Coding a hypothetical vertex shader

    Finishing the CameraGraphics class

    Breaking up the new draw code

    Coding a shader for the game

    Running the completed game

    Summary

    Further reading

    Other Books You May Enjoy

    Index

    Landmarks

    Cover

    Index

    Preface

    Always dreamed of creating your own games? With the third edition of Beginning C++ Game Programming, you can turn that dream into reality! This beginner-friendly guide is updated and improved to include the latest features of VS 2022, SFML, and modern C++20 programming techniques. You will get a fun introduction to game programming by building four fully playable games of increasing complexity. You’ll build clones of popular games such as Timberman, Pong, a Zombie survival shooter, and an endless runner.

    The book starts by covering the basics of programming. You’ll study key C++ topics, such as object-oriented programming (OOP) and C++ pointers, and get acquainted with the Standard Template Library (STL). The book helps you learn about collision detection techniques and game physics by building a Pong game. As you build games, you’ll also learn exciting game programming concepts such as vertex arrays, directional sound (spatialization), OpenGL programmable shaders, spawning objects, and much more. You’ll dive deep into game mechanics and implement input handling, levelling up a character, and simple enemy AI. Finally, you’ll explore game design patterns to enhance your C++ game programming skills.

    By the end of the book, you’ll have gained the knowledge you need to build your own games with exciting features from scratch.

    Who this book is for

    This book is perfect for you if you have no C++ programming knowledge, you need a beginner-level refresher course, or you want to learn how to build games or just use games as an engaging way to learn C++.

    Whether you aspire to publish a game (perhaps on Steam) or just want to impress friends with your creations, you’ll find this book useful.

    What this book covers

    Chapter 1, Welcome to Beginning C++ Game Programming, Third Edition: This chapter outlines the journey to writing exciting games for PC using C++ and the OpenGL powered SFML. This third edition has an overwhelming focus on improving and expanding upon what you will learn in game programming. All the C++ basics from variables in the beginning, through loops, object-oriented programming, the Standard Template Library, SFML features, and newer C++ possibilities, have been added to and expanded upon. By the end of this book, you will not only have four playable games but also have a deep and solid grounding in C++.

    Chapter 2, Variables, Operators, and Decisions: Animating Sprites: In this chapter, we will do quite a bit more drawing on the screen. We will animate some clouds that travel at a random height and a random speed across the background and a bee that does the same in the foreground. To achieve this, we will need to learn some more of the basics of C++. We will be learning how C++ stores data with variables as well as how to manipulate those variables with the C++ operators and how to make decisions that branch our code on different paths based on the value of variables. Once we have learned all this, we will be able to reuse our knowledge about the SFML

    Sprite

    and

    Texture

    classes to implement our cloud and bee animations.

    Chapter 3, C++ Strings, SFML Time, Player Input, and HUD: In this chapter, we will spend around half the time learning how to manipulate text and display it on the screen and the other half looking at timing and how a visual time bar can inform the player and create a sense of urgency in the game.

    Chapter 4, Loops, Arrays, Switch, Enumerations, and Functions – Implementing Game Mechanics: This chapter probably has more C++ information than any other chapter in the book. It is packed with fundamental concepts that will move our understanding on enormously. It will also begin to shed light on some of the murky areas we have been skipping over a little bit, like functions, the game loop, and loops in general.

    Chapter 5, Collisions, Sound, and End Conditions: Making the Game Playable: This is the final phase of the first project. By the end of this chapter, you will have your first completed game. Once you have Timber!!! up and running, be sure to read the last section of this chapter as it will suggest ways to make the game better. Here is what we will cover in this chapter: adding the rest of the sprites, handling the player input, animating the flying log, handling death, adding sound effects, adding features, and improving Timber!!!.

    Chapter 6, Object-Oriented Programming – Starting the Pong Game: In this chapter, there’s a little bit of theory, but the theory will give us the knowledge that we need to start using object-oriented programming (OOP). OOP helps us organize our code into human-recognizable structures and handle complexity. We will not waste any time in putting that theory to good use as we will use it to code the next project, a Pong game. We will get to look behind the scenes at how we can create new C++ types that we can use as objects. We will achieve this by coding our first class. To get started, we will look at a simplified Pong game scenario so that we can learn about some class basics, and then we will start again and code a Pong game for real using the principles we have learned.

    Chapter 7, AABB Collision Detection and Physics – Finishing the Pong Game: In this chapter, we will code our second class. We will see that although the ball is obviously quite different from the bat, we will use the exact same techniques to encapsulate the appearance and functionality of a ball inside a

    Ball

    class, just like we did with the bat and the

    Bat

    class. We will then add the finishing touches to the Pong game by coding some collision detection and scorekeeping. This might sound complicated but as we are coming to expect, SFML will make things much easier than they otherwise would be.

    Chapter 8, SFML Views – Starting the Zombie Shooter Game: In this project, we will be making even more use of OOP, and to a powerful effect. We will also be exploring the SFML

    View

    class. This versatile class will allow us to easily divide our game up into layers for different aspects of the game. In the Zombie Shooter project, we will have a layer for the HUD and a layer for the main game. This is necessary because the game world expands each time the player clears a wave of zombies. Eventually, the game world will be bigger than the screen and the player will need to scroll. The use of the

    View

    class will prevent the text of the HUD from scrolling with the background.

    Chapter 9, C++ References, Sprite Sheets, and Vertex Arrays: In Chapter 4, Loops, Arrays, Switch, Enumerations, and Functions – Implementing Game Mechanics, we talked about scope. This is the concept that variables declared in a function or inner block of code only have scope (that is, can be seen or used) in that function or block. Using only the C++ knowledge we have currently, this can cause a problem. What do we do if we need to work on a few complex objects that are needed in the

    main

    function? This could imply all the code must be in the

    main

    function.

    In this chapter, we will explore C++ references, which allow us to work on variables and objects that are otherwise out of scope. In addition to this, these references will help us avoid having to pass large objects between functions, which is a slow process. It is slow because each time we do this, a copy of the variable or object must be made.

    Armed with this new knowledge of references, we will look at the SFML

    VertexArray

    class, which allows us to build up a large image that can be quickly and efficiently drawn to the screen using multiple parts in a single image file. By the end of this chapter, we will have a scalable, random, scrolling background that’s been made using references and a

    VertexArray

    object.

    Chapter 10, Pointers, the Standard Template Library, and Texture Management: In this chapter, we will learn a lot as well as get plenty done in terms of the game in this chapter. We will first learn about the fundamental C++ topic of pointers. Pointers are variables that hold a memory address. Typically, a pointer will hold the memory address of another variable. This sounds a bit like a reference, but we will see how they are much more powerful and use a pointer to handle an ever-expanding horde of zombies.

    We will also learn about the Standard Template Library (STL), which is a collection of classes that allow us to quickly and easily implement common data management techniques.

    Chapter 11, Coding the TextureHolder Class and Building a Horde of Zombies: Now that we have understood the basics of the STL, we will be able to use that new knowledge to manage all the textures from the game because if we have 1,000 zombies, we don’t really want to load a copy of a zombie graphic into the GPU for each and every one.

    We will also dig a little deeper into OOP and use a static function, which is a function of a class that can be called without an instance of the class. At the same time, we will see how we can design a class to ensure that only one instance can ever exist. This is ideal when we need to guarantee that different parts of our code will use the same data.

    Chapter 12, Collision Detection, Pickups, and Bullets: So far, we have implemented the main visual aspects of our game. We have a controllable character running around in an arena full of zombies that chase them. The problem is that they don’t interact with each other. A zombie can wander right through the player without leaving a scratch. We need to detect collisions between the zombies and the player.

    If the zombies are going to be able to injure and eventually kill the player, it is only fair that we give the player some bullets for their gun. We will then need to make sure that the bullets can hit and kill the zombies.

    At the same time, if we are writing collision detection code for bullets, zombies, and the player, it would be a good time to add a class for health and ammo pickups as well.

    Here is what we will do and the order in which we will cover things in this chapter: shooting bullets, adding a crosshair and hiding the mouse pointer, spawning pickups, and detecting collisions

    Chapter 13, Layering Views and Implementing the HUD: In this chapter, we will get to see the real value of SFML

    Views

    . We will add a selection of SFML

    Text

    objects and manipulate them as we did before in the Timber!!! project and the Pong project. What’s new is that we will draw the HUD using a second View instance. This way, the HUD will stay neatly positioned over the top of the main game action, regardless of what the background, player, zombies, and other game objects are doing.

    Chapter 14, Sound Effects, File I/O, and Finishing the Game: We are nearly done with this project. This short chapter will demonstrate how we can easily manipulate files stored on the hard drive using the C++ standard library, and we will also add sound effects. Of course, we know how to add sound effects, but we will discuss exactly where the calls to the

    play

    function will go in the code. We will also tie up a few loose ends to make the game complete. In this chapter, we will cover the following topics: saving and loading the hi-score using file input and file output, adding sound effects, allowing the player to level up, and spawning a new wave.

    Chapter 15, Run!: Welcome to the final project. Run, Run is an endless runner where the objective of the player is to stay ahead of the disappearing platforms that are catching them up from behind. In this project, we will learn loads of new game programming techniques and even more C++ topics to implement those techniques. Perhaps the best improvement this game will have over the previous games is that it will be way more object oriented than any of the others. There will be many, many more classes than any of the preceding projects but most of the code files for these classes will be short and uncomplicated. Furthermore, we will build a game where the functionality and appearance of all the in-game objects is pushed out to classes, leaving the main game loop unchanged regardless of what the

    GameObjects

    do. This is powerful because it means you can make a hugely varied game just by designing new standalone components (classes) that describe the behavior and appearance of the required game entity. This means you can use the same code structure for a completely different game of your own design. But there is way more to come than just this. Read on for details.

    Chapter 16, Sound, Game Logic, Inter-Object Communication, and the Player: In this chapter, we will quickly implement our game’s sound. We have done this before, so it won’t be hard. In fact, in just half a dozen lines of code, we will also add music to our sound features. Later in the project, but not in this chapter, we will add directional (spatialized) sound.

    In this chapter, we will wrap all our sound-related code into a single class called

    SoundEngine

    . Once we have some noise, we will then move on to get started on the player. We will achieve the entire player character functionality just by adding two classes: one that extends

    Update

    and one that extends

    Graphics

    . This creation of new game objects by extending these two classes will be how we do almost everything else for the entire game. We will also see the simple way that objects communicate with each other using pointers.

    Chapter 17, Graphics, Camera, Action: In this chapter, we will talk in depth about the way the graphics will work in this project. As we will be coding the cameras that do the drawing in this chapter, now seems like a good time to talk about the graphics too. If you looked in the

    graphics

    folder, there is just one graphic. Furthermore we are not calling

    window.draw

    at any point in our code so far. We will discuss why draw calls should be kept to a minimum as well as implement our

    Camera

    classes that will handle this for us. Finally, in this chapter, we will be able to run the game and see the cameras in action, including the main view, the radar view, and the timer text.

    Chapter 18, Coding the Platforms, Player Animations, and Controls: In this chapter, we will code the platforms and the player animation and controls. In my opinion, we have done the hard work already and most of what follows has a much higher reward-to-effort ratio. Hopefully this chapter will be interesting as we will see how the platforms will ground the player and enable them to run, as well as seeing how we loop through the frames of animation to create a smooth running effect for the player. We will do the following: coding the platforms, adding functionality to the player, coding the

    Animator

    class, coding the animations, and adding a smooth running animation to the player.

    Chapter 19, Building the Menu and Making It Rain: In this chapter, we will implement two significant features. One is a menu screen to keep the player informed of their options for starting, pausing, restarting, and quitting the game. The other job will be to create a simple raining effect. You could argue the raining effect isn’t necessary, even that it doesn’t fit the game, but it is easy, fun, and a good trick to learn. What you should expect by now, and yet is still perhaps the most interesting aspect of this chapter, is how we will achieve both these objectives by coding classes derived from

    Graphics

    and

    Update

    , composing them in

    GameObject

    instances, and they will just work alongside all our other game entities.

    Chapter 20, Fireballs and Spatialization: In this chapter, we will be adding all the sound effects and the HUD. We have done this in two of the previous projects, but we will do things a bit differently this time. We will explore the concept of sound spatialization and how SFML makes this complicated concept nice and easy. In addition, we will build a HUD class to encapsulate our code that draws information to the screen.

    Chapter 21, Parallax Backgrounds and Shaders: This is the last chapter and our last opportunity to work on our game. It will be fully playable with all the features by the end. Here is what we will do to wrap up the Run game. We will learn a bit more about OpenGL, shaders, and the Graphics Library Shading Language (GLSL), finish the

    CameraGraphics

    class by implementing a scrolling background and shader, a code a shader by using someone else’s code, and finally run the completed game

    To get the most out of this book

    There are no knowledge prerequisites for this book. You do not need to know how to program as the book takes you from zero knowledge to four playable games. It will help a little if you have played a few video games and you are determined to learn.

    Download the example code files

    The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/Beginning-C-Game-Programming-Third-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Download the color images

    We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/gbp/9781835081747.

    Conventions used

    There are a number of text conventions used throughout this book.

    CodeInText

    : Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: "My main project directory is

    D:\VS Projects\Timber

    ."

    A block of code is set as follows:

    int

    playerScore =

    0

    ;

    char

    playerInitial =

    'J'

    ;

    float

    valuePi =

    3.141f

    ;

    bool

    isAlive =

    true

    ;

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    // Make a tree sprite

    Texture textureTree;

    textureTree.

    loadFromFile

    (

    graphics/tree.png

    );

    Sprite spriteTree;

    spriteTree.

    setTexture

    (textureTree);

    spriteTree.

    setPosition

    (

    810

    ,

    0

    );

    while

    (window.

    isOpen

    ()) {

    Any command-line input or output is written as follows:

    # cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf

    Bold: Indicates a new term, an important word, or words that you see on the screen. For instance, words in menus or dialog boxes appear in the text like this. For example: "Select System info from the Administration panel."

    Warnings or important notes appear like this.

    Tips and tricks appear like this.

    Get in touch

    Feedback from our readers is always welcome.

    General feedback: Email

    [email protected]

    and mention the book’s title in the subject of your message. If you have questions about any aspect of this book, please email us at

    [email protected]

    .

    Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you reported this to us. Please visit http://www.packtpub.com/submit-errata, click Submit Errata, and fill in the form.

    Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at

    [email protected]

    with a link to the material.

    If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

    Share your thoughts

    Once you’ve read Beginning C++ Game Programming, Third Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

    Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

    Download a free PDF copy of this book

    Thanks for purchasing this book!

    Do you like to read on the go but are unable to carry your print books everywhere?

    Is your eBook purchase not compatible with the device of your choice?

    Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

    Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

    The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily.

    Follow these simple steps to get the benefits:

    Scan the QR code or visit the link below:

    https://packt.link/free-ebook/9781835081747

    Submit your proof of purchase.

    That’s it! We’ll send your free PDF and other benefits to your email directly.

    1

    Welcome to Beginning C++ Game Programming Third Edition!

    Let’s get started on your journey to writing exciting games for the PC using C++ and the OpenGL-powered SFML. This third edition has an overwhelming focus on improving and expanding upon what you will learn. All the C++ basics from variables in the beginning, through loops, object-oriented programming, the Standard Template Library, SFML features, and newer C++ possibilities have all been added to and expanded upon. By the end of this book, not only will you have four playable games but you will also have a deep and solid grounding in C++.

    Here is what is coming up in this chapter

    First, we will look at the four games we will build across this book. The first game is the exact same as the previous edition and will help us learn the C++ basics, like variables, loops, and decision-making. The second and third are enhanced, modified, and refined from the previous edition, and the fourth is all new and, in my view, way better for playing and learning than the final two games of the previous edition put together.

    This next bit is mportant in which you will discover why you should learn game programming and perhaps any other programming genre using C++. Using C++ to learn game development can be the best choice for so many reasons.

    Then, we can explore SFML and its relationship with C++.

    Nobody likes corporate evangelism, and you won’t get any here, but there are good reasons to find out about Microsoft Visual Studio and why we will use it in this book.

    Next, it’s time to set up the development environment. This is admittedly a slightly dull affair, but we will get through it in short order, step by step, and when you have done it once, you will never need to learn it again.

    We will then plan and prepare for the first game project, Timber!!!

    Moving on, we will write the first C++ code of this book and make a runnable first stage of the game that draws a pretty background – ooh! In the next chapter, things will advance and begin to move graphics around and what we learned in this chapter will stand us in good stead to make faster progress with our first game.

    Finally, we will cover how to handle any problems you might get as you learn C++ and game programming, such as configuration errors, compile errors, link errors, and bugs.

    Of course, what you want to know first is what you are going to have to show for yourself by the end of this weighty tome. So, let’s find out more about the games we will build.

    You will find this chapter’s source code in the GitHub repository: https://github.com/PacktPublishing/Beginning-C-Game-Programming-Third-Edition/tree/main/Timber

    The games we will build

    This journey will be smooth as we will learn about the fundamentals of the super-fast C++ language one step at a time, and then put this new knowledge to use by adding cool features to the four games we are going to build.

    The following are our four projects for this book.

    Timber!!!

    The first game is an addictive, fast-paced clone of the hugely successful Timberman. Our game, Timber!!!, will introduce us to all the beginner basics of C++ while we build a genuinely playable game. Here is what our version of the game will look like when we are done and we have added a few last-minute enhancements:

    A video game with a person standing in front of trees Description automatically generated

    Figure 1.1: Timber game

    Timberman can be found at http://store.steampowered.com/app/398710/.

    Pong

    Pong was one of the first video games ever made. It is an excellent example of how the basics of game object animation, player input, and collision detection work. We will build a version of this simple retro game to explore the concept of classes and object-oriented programming. Here is what it will look like by the end of Chapter 7:

    A black screen with white text Description automatically generated

    Figure 1.2: Pong game

    The player will use the bat at the bottom of the screen and hit the ball back to the top of the screen. If you are interested, find out about Pong’s history here: https://en.wikipedia.org/wiki/Pong.

    Zombie Arena

    Next, we will build a frantic, zombie survival shooter, not unlike the Steam hit Over 9,000 Zombies!, which you can find out more about at http://store.steampowered.com/app/273500/. The player will have a machine gun and must fight off ever-growing waves of zombies. All this will take place in a randomly generated, scrolling world:

    A video game screen shot Description automatically generated

    Figure 1.3: Zombie Arena game

    To achieve this, we will learn about how object-oriented programming allows us to have a large code base (lots of code) that is easy to write and maintain. Expect exciting features such as hundreds of enemies, rapid-fire weaponry, pickups, and a character that can be leveled up after each wave.

    Platform game

    The final game is a platform game called Run. Run will be packed with more features enabled by the C++ skills we will have acquired and made easier by the great features of SFML. Take a look at the finished game below:

    A video game with a person walking on a bridge Description automatically generated

    Figure 1.4: Platform game

    Features include a photo-realistic shader background, parallax scrolling cityscape, spatialized (directional) sound, mini-map, animated player character, rain weather effect, music, pop-up menu, and more. Best of all, the final game will have a reusable code structure that you can use to invent and add your own features to.

    Why you should learn game programming using C++ in 2024

    The title above could also have read, Why use game programming to learn C++…, because C++, game programming, and beginners (in my view) are a perfect match. Let’s look at C++ in more detail while also staying focussed on games and beginners:

    Speed: C++ is known for its high performance and efficiency. In game development, performance is important. C++ allows you to write code that can run close to the native languages of both the CPU and the GPU, making it well suited for anything demanding, which includes games. This is achieved because C++ is turned into native executable instructions. This is just what we need when coding games with hundreds, thousands, or even hundreds of thousands of entities in it. In the final chapter, Chapter 21, we will see how C++ can interact directly with the GPU using shader programs.

    Cross-platform development: C++ works almost everywhere, meaning you can write code that can be compiled and run on various platforms without significant modifications. This book will focus on Windows but everything we learn and write in this book, with minor modifications, will work on macOS and Linux. C++ itself is also used extensively in next-gen console game development and can even be useful on mobile. Compiled means translating our C++ code into binary machine instructions for the CPU.

    Lots of game engines and libraries: Many game engines and libraries are written in C++ or provide C++ APIs. Learning C++ gives you access to the widest range of tools and resources for game development, such as Unreal Engine, as well as the fastest and best graphics libraries like Vulcan, OpenGL, DirectX, and Metal, as well as physics libraries like Box2D, UI tools like IMGUI, and networking libraries for co-op and multiplayer like RakNet, Enet and SFML’s very own networking features.

    Low-level control: C++ provides low-level control over hardware resources, which is crucial for optimizing game performance. In game development, you may need to manage memory, optimize rendering pipelines, and maintain control over the system your game is running on, and C++ offers the flexibility and power to do this. If managing memory and rendering pipelines sound ominous, then I can assure you that things will be fine. We introduce both these topics in a completely beginner-friendly manner in Chapters 10 and 21, respectively. Far from leaving you baffled, knowing how these powerful things can be controlled will leave you feeling powerful and in control of your programming destiny.

    Documentation and support: There is a thriving community around C++ game development, with numerous resources, tutorials, and forums available to help you learn and troubleshoot issues. If you have a C++ problem, I can guarantee you are not the first and a quick web search will almost always yield a solution. ChatGPT is an ace C++ problem solver, too.

    Learning C++ does have challenges but, taken a step at a time, is easily mastered. It is so rewarding to struggle over a problem and finally see it burst into an exciting gameplay feature when you get it right. Game development often involves seemingly difficult algorithms, data structures, and principles but C++ provides tools like the Standard Template Library (STL) and classes through object-oriented programming (OOP) to boil down complexity into manageable chunks. We will be covering OOP and STL in Chapters 6 and 10, respectively.

    C++ is an industry standard: It is because of everything we have just discussed that C++ is widely used in the game development industry. Familiarity with C++ can make it easier to collaborate with other developers, understand existing code bases, switch between game engines, and secure highly paid jobs in the industry.

    Critics will say that C++ can have a steeper learning curve compared to some other programming languages and that if you’re new to programming or game development, you might consider starting with a more beginner-friendly language like C# (for Unity development) or Python (for simple game projects) before diving into C++. There is some truth in this, but it is nowhere near as true as it used to be. C++ is constantly evolving, and numerous improvements to simplify learning and dramatically speed up development have been introduced in recent years. For example, new keywords like auto, intriguing-sounding logic operators like spaceship, as well as language constructs like lambdas, coroutines, and smart pointers, were introduced over the last 10 years, which dramatically simplify and speed up C++ development.

    In summary, I would suggest that not learning C++ as a first language might be a mistake. And if you want to make learning as fun and rewarding as it possibly can get then learning with games is a no-brainer. Finally, if you want to be an indie game developer or work for a top game studio, unless you have some very specific other path in mind, C++ is the way to go.

    But having just stated that C++ is so wonderful and has so many paths and libraries, why would we choose SFML?

    SFML

    SFML is the Simple Fast Media Library. It is not the only C++ library for games and multimedia. It is possible to make an argument to use other libraries, but SFML seems to come through for me every time. Firstly, it is written using object-oriented C++. The benefits of object-oriented C++ are numerous, and you will experience them as you progress through this book.

    SFML is also easy to get started with and is therefore a good choice if you are a beginner, yet at the same time, it has the potential to build the highest quality 2D games if you are a professional. So, a beginner can get started using SFML and not worry about having to start again with a new language/library as their experience grows. And if you want to build 3D games, C++ and SFML is a great introduction before moving on to Unreal Engine. As an aside, you can build 3D games with SFML and OpenGL but most SFML libraries are focused on 2D, as is this book.

    Perhaps the biggest benefit is that most modern C++ programming uses OOP. Every C++ beginner’s guide I have ever read uses and teaches OOP. OOP is the future (and the now) of coding in almost all languages, in fact. So why, if you’re learning C++ from the beginning, would you want to do it any other way?

    SFML has a library for just about anything you would ever want to do in a 2D game. SFML works using OpenGL, which can also make 3D games. OpenGL is the de facto free-to-use graphics library for games when you want it to run on more than one platform. When you use SFML, you are automatically using OpenGL.

    SFML allows you to create the following:

    2D graphics and animations, including scrolling game worlds.

    Sound effects and music playback, including high-quality directional sound.

    Input handling with a keyboard, mouse, and gamepad.

    Online multiplayer features.

    The same code can be compiled and linked on all major

    Enjoying the preview?
    Page 1 of 1