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
Beginning C++ Game Programming
Beginning C++ Game Programming

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

eBook
€20.98 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.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

Beginning C++ Game Programming

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 Simple and fast Multimedia Library (SFML) Sprite and Texture classes to implement our cloud and bee animations.

In summary, here is what is in store:

  • Learning all about C++ variables
  • Seeing how to manipulate the variables
  • Adding clouds, a buzzing bee and a tree for the player to chop away at
  • Random numbers
  • Making...

Learning all about C++ variables

Variables are the way that our C++ games store and manipulate the values/data in our game. If we want to know how much health the player has, we need a variable. Perhaps you want to know how many zombies are left in the current wave? That is a variable as well. If you need to keep track of the name of the player who got a specific high score, you guessed it, we need a variable for that. Is the game over or still playing? Yep, that’s a variable too.

Variables are named identifiers to locations in memory. So, we might name a variable called numberOfZombies, and that variable could refer to a place in memory that stores a value to represent the number of zombies that are remaining in the current wave.

The way that computer systems address locations in memory is complex. Programming languages use variables to give a human-friendly way to manage our data in that memory. Managing a complex system in a human-friendly way is really what programming...

Seeing how to manipulate the variables

At this point, we know exactly what variables are, the main types they can be, and how to declare and initialize them. We still haven’t learned to achieve much with them, however. We need to manipulate our variables, add them, take away, multiply, divide, and especially, test them.

First, we will deal with how we can manipulate them and later we will look at how and why we test them.

With this in mind, let’s learn about the C++ arithmetic and assignment operators.

C++ arithmetic and assignment operators

To manipulate variables, C++ has a range of arithmetic operators and assignment operators. Fortunately, most arithmetic and assignment operators are quite intuitive to use, and those that aren’t are quite easy to explain. To get us started, let’s look at a table of arithmetic operators followed by a table of assignment operators that we will regularly use throughout this book.

...

Adding clouds, a buzzing bee, and a tree

First, we will add a tree. This is going to be easy. The reason for this is because the tree doesn’t move. We will use the same procedure that we used in the previous chapter when we drew the background. In this next section, we will prepare our static tree sprite and our moving bee and cloud sprites. We can then focus separately on moving and drawing the bee and the clouds because they will need a bit more C++ knowledge to do so.

Preparing the tree

Add the following highlighted code. Notice the un-highlighted code, which is the code we have already written. This should help you identify that the new code should be typed immediately after we set the position of the background but before the start of the main game loop. We will recap what is going on in the new code after you have added it.

int main()
{
// Create a video mode object
VideoMode vm(1920, 1080);
// Create and open a window for the game
RenderWindow window(vm,...

Random numbers

Random numbers are useful for lots of reasons in games, for example, determining what card the player is dealt or how much damage within a certain range is subtracted from an enemy’s health. As hinted at, we will use random numbers to determine the starting location and speed of the bee and the clouds.

Generating random numbers in C++

To generate random numbers, we will need to use some more C++ functions. Don’t add any code to the game yet. Let’s just look at the syntax and the steps required with some hypothetical code.

Computers can’t genuinely pick random numbers. They can only use algorithms to pick a number that appears to be random. So that this algorithm doesn’t constantly return the same value, we must seed the random number generator. The seed can be any integer number, although it must be a different seed each time you require a unique random number. Look at this code, which seeds the random number generator...

Making decisions with if and else

The C++ if and else keywords are what enable us to make decisions. We saw if in action in the previous chapter when we detected each frame whether the player had pressed the Escape key.

if (Keyboard::isKeyPressed(Keyboard::Escape))
{
window.close();
}

So far, we have seen how we can use arithmetic and assignment operators to create expressions. Now, we can see some new operators.

Logical operators

Logical operators are going to help us make decisions, by building expressions that can be tested for a value of either true or false. At first, this might seem like quite a narrow choice and insufficient for the kind of choices that might be needed in an advanced PC game. Once we dig a little deeper, we will see that you can make all the required decisions we will need, with just a few of the logical operators.

Here is a table of the most useful logical operators. Look at them and the associated examples, and then we will see how to...

Timing

Before we can move the bee and the clouds, we need to consider timing. As we already know, the main game loop executes repeatedly until the player presses the Escape key.

We have also learned that C++ and SFML are exceptionally fast. In fact, my modest laptop executes a simple game loop (like the current one) at around five thousand times per second. With this in mind, let’s discuss the problem of making the rate at which each frame of animation is shown consistent and predetermined.

The frame rate problem

Let’s consider the speed of the bee. For discussion, we could pretend that we are going to move it at 200 pixels per second. On a screen that is 1920 pixels wide, it would take, approximately, 10 seconds to cross the entire width, because 10 x 200 is 2000 (near enough to 1920).

Furthermore, we know that we can position any of our sprites with setPosition(...,...). We just need to put the x and y coordinates in the parentheses.

In addition...

Moving the clouds and the bee

Let’s use the elapsed time since the last frame to breathe life into the bee and the clouds. This will solve the problem of needing to achieve a consistent frame rate across different PCs.

Giving life to the bee

The first thing we want to do is set up the bee at a certain height and a certain speed. We only want to do this when the bee is inactive. So, we wrap the next code in an if block. Examine and add the highlighted code, and then we will discuss it.

/*
****************************************
Update the scene
****************************************
*/
// Measure time
Time dt = clock.restart();
// Setup the bee
if (!beeActive)
{
// How fast is the bee
srand((int)time(0));
beeSpeed = (rand() % 200) + 200;
// How high is the bee
srand((int)time(0) * 10);
float height = (rand() % 500) + 500;
spriteBee.setPosition(2000, height);
beeActive = true;
}
/*
****************************************
Draw the scene
***********************...

Summary

In this chapter, we learned that a variable is a named storage location in memory, in which we can keep values of a specific type. Types include int, float, double, bool, String, and char.

We can declare and initialize all the variables we need to store the data for our game. Once we have our variables, we can manipulate them using the arithmetic and assignment operators as well as use them in tests with the logical operators. Used in conjunction with the if and else keywords, we can branch execution of our code depending upon the current situation in the game.

Using all this new knowledge, we animated some clouds and a bee. In the next chapter, we will use these skills some more to add a heads-up display (HUD) and add more input options for the player, as well as represent time visually using a time bar.

Frequently Asked Questions

Q) Why do we set the bee to inactive when it gets to -100? Why not just zero because zero is the left-hand side of the window?

A) The bee graphic is 60 pixels wide and its origin is at the top left pixel. As a result, when the bee is drawn with its origin at x equals zero, the entire bee graphic is still on screen for the player to see. By waiting until it is at -100, we can be sure it is out of the player’s view.

Q) How do I know how fast my game loop is?

A) If you have a modern NVIDIA graphics card you might be able to already by configuring your GeForce Experience overlay to show the frame rate. To measure this explicitly using our own code, however, we will need to learn a few more things. We will add the ability to measure and display the current frame rate in Chapter 5, Collisions, Sound, and End Conditions: Making the Game Playable.

Q) What is the difference between the assignment operator, =, and the equality operator, ==,...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create fun games in C++, with this up-to-date guide covering the latest features of C++20 and VS2022
  • Build clones of popular games such as a Timberman clone, a Pong game, a Zombie Survival Shooter, and a platform endless runner game
  • Discover tips to expand your finished games by thinking critically, technically, and creatively

Description

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'll 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 is this book 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 you will learn

  • Set up your game project in VS 2022 and explore C++ libraries such as SFML
  • Build games in C++ from the ground up, including graphics, physics, and input handling
  • Implement core game concepts such as game animation, game physics, collision detection, scorekeeping, and game sound
  • Implement automatically spawning objects and AI to create rich and engaging experiences
  • Learn advanced game development concepts, such as OpenGL shaders, texture atlases, and parallax backgrounds
  • Scale and reuse your game code with modern game programming design patterns

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 31, 2024
Length: 648 pages
Edition : 3rd
Language : English
ISBN-13 : 9781835088258
Languages :
Concepts :

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 : May 31, 2024
Length: 648 pages
Edition : 3rd
Language : English
ISBN-13 : 9781835088258
Languages :
Concepts :

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 113.97
Mastering Linux Administration
€37.99
Beginning C++ Game Programming
€37.99
The Machine Learning Solutions Architect Handbook
€37.99
Total 113.97 Stars icon

Table of Contents

23 Chapters
Welcome to Beginning C++ Game Programming Third Edition! Chevron down icon Chevron up icon
Variables, Operators, and Decisions: Animating Sprites Chevron down icon Chevron up icon
C++ Strings, SFML Time: Player Input and HUD Chevron down icon Chevron up icon
Loops, Arrays, Switch, Enumerations, and Functions: Implementing Game Mechanics Chevron down icon Chevron up icon
Collisions, Sound, and End Conditions: Making the Game Playable Chevron down icon Chevron up icon
Object-Oriented Programming – Starting the Pong Game Chevron down icon Chevron up icon
AABB Collision Detection and Physics – Finishing the Pong Game Chevron down icon Chevron up icon
SFML Views – Starting the Zombie Shooter Game Chevron down icon Chevron up icon
C++ References, Sprite Sheets, and Vertex Arrays Chevron down icon Chevron up icon
Pointers, the Standard Template Library, and Texture Management Chevron down icon Chevron up icon
Coding the TextureHolder Class and Building a Horde of Zombies Chevron down icon Chevron up icon
Collision Detection, Pickups, and Bullets Chevron down icon Chevron up icon
Layering Views and Implementing the HUD Chevron down icon Chevron up icon
Sound Effects, File I/O, and Finishing the Game Chevron down icon Chevron up icon
Run! Chevron down icon Chevron up icon
Sound, Game Logic, Inter-Object Communication, and the Player Chevron down icon Chevron up icon
Graphics, Cameras, Action Chevron down icon Chevron up icon
Coding the Platforms, Player Animations, and Controls Chevron down icon Chevron up icon
Building the Menu and Making It Rain Chevron down icon Chevron up icon
Fireballs and Spatialization Chevron down icon Chevron up icon
Parallax Backgrounds and Shaders Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(23 Ratings)
5 star 73.9%
4 star 17.4%
3 star 0%
2 star 4.3%
1 star 4.3%
Filter icon Filter
Top Reviews

Filter reviews by




Tone Jun 03, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
"Beginning C++ Game Programming - Third Edition" is a perfect starting point for beginners eager to dive into game development. Updated for C++20 and Visual Studio 2022, it explains essential programming concepts through hands-on projects like Pong, Timberman, and a Zombie survival shooter. The step-by-step instructions cover basics like object-oriented programming and collision detection, and extend to advanced topics such as OpenGL shaders and AI. This engaging approach ensures readers not only learn C++, but also create some fun, fully playable games. I definitely recommend.
Amazon Verified review Amazon
Alex Sep 13, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is perfect. The examples are well-explained and the hands-on approach keeps you engaged. Plus, if you buy the book, you get a free PDF version as well.
Amazon Verified review Amazon
Jason Skillman Jul 24, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book covers both worlds of c++ and game development. If you are a beginner or have been programming for years, then I highly recommend getting this book to further your learning in the C++ programming language and game development. You will master the basics of C++ and learn about variables, basic loops, if statements, classes, methods, and inheritance. The book even covers learning about pointers and references which are essential to mastering C++. Another topic which I appreciate is how to create a new project and configure solution settings. This is also a skill that every C++ programmer needs but no other book covers. Regarding game development, you will have multiple complete games and projects to put on your portfolio when you have finished reading. I definitely recommend this book if you are new or experienced.
Amazon Verified review Amazon
SAO Jun 30, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was excited to read this book so my opinions may be a little biased based off the topic. First off I have always wanted to makes games without an engine like Unreal or Unity. This book was promised to take you down that rabbit hole. So I was very excited. The book seems very well thought out. I did notice a few times there were paragraphs that probably could have been cut because it didn’t serve a major purpose in the book, but it was still engaging.I like how the book has you plan and document the process of making the game before you start to get you in the right habits. The author explains the process after but getting a game plan before the game is important. Lastly the author assumes you don’t have any C++ knowledge but any programming knowledge is beneficial because you can see where the author is going with his instructions. You can do without, but you will enjoy the book with some background knowledge.If you want to learn how to make games from near scratch, then this book is great.
Amazon Verified review Amazon
Osher Vaknin Oct 07, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is really good for people who want to learn C++/Game Development as it's title suggests, the explanations in the book are very well done, abstracting subjects so that the beginner can gradually learn harder concepts, I will definitely recommend this book if you're a beginner.
Amazon Verified review Amazon