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 2: Variables, Operators, and Decisions – Animating Sprites

In this chapter, we will do quite a bit more drawing on the screen and, to achieve this, we will need to learn about some of the basics of C++. We will learn how to use variables to remember and manipulate values, and we will begin to add more graphics to the game. As this chapter progresses, we will find out how we can manipulate these values to animate the graphics. These values are known as variables.

Here is what is in store:

  • Learning all about C++ variables
  • Seeing how to manipulate the values stored in variables
  • Adding a static tree graphic, ready for the player to chop away at
  • Drawing and animating a bee and three clouds

C++ variables

Variables are the way that our C++ games store and manipulate values/data. 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 remember the name of the player who got a high score, you guessed it—we need a variable for that. Is the game over or still playing? Yes, that's a variable too.

Variables are named identifiers for locations in the memory of the PC. The memory of the PC is where computer programs are stored as they are being executed. So, we might name a variable numberOfZombies and that variable could refer to a place in memory that stores a value to represent the number of zombies that are left in the current wave.

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

The small amount we have...

Manipulating 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 can't do that much with them, however. We need to manipulate our variables; add them; take them away; and multiply, divide, and test them.

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

C++ arithmetic and assignment operators

In order 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, all of which we will regularly use throughout this book:

And now for the assignment operators:

Important note

Technically, all of these operators...

Adding clouds, a tree, and a buzzing bee

In this section, we will add clouds, a tree, and a buzzing bee to our Timber!!! game. 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. The bee and the clouds will also be easy to draw in their starting positions, but we will need to combine what we have just learned about manipulating variables with some new C++ topics to make them move.

Preparing the tree

Let's get ready to draw the tree! Add the following highlighted code. Notice the unhighlighted code, which is the code we have already written. This should help you to 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 provide a recap regarding what is going on in the new code after we have added it:

int main()
{
 ...

Random numbers

Random numbers are useful for lots of reasons in games—perhaps determining what card the player is dealt or how much damage within a certain range is subtracted from an enemy's health. We will now learn how to generate 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—two more, to be precise. Don't add any code to the game yet. Let's just look at the syntax and the steps that are required with some hypothetical code.

Computers can't genuinely pick random numbers. They can only use algorithms/calculations 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 the...

Making decisions with if and else

The C++ if and else keywords are what allow us to make decisions. We have already seen if in action in the previous chapter when we detected whether the player had pressed the Esc key each frame:

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 will look at some new operators.

Logical operators

Logical operators are going to help us to 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 we can make all of 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...

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 aging laptop executes a simple game loop (like the current one) at around five thousand times per second.

The frame rate problem

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

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

In addition to setting the position of a sprite, we can also get the current position of a sprite. To get the horizontal x coordinate of...

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 having 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. Due to this, we will wrap the following code in an if block. Examine and add the following 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(...

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. The types include int, float, double, bool, String, and char.

We can declare and initialize all of 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 our code depending on the current situation in the game.

Using all of 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.

FAQ

Q) Why do we set the bee to inactive when it gets to -100? Why not just zero since 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.

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}