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 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.

In this chapter, we will cover the following topics:

  • Adding the rest of the sprites
  • Handling the player input
  • Animating the flying log
  • Handling death
  • Adding sound effects
  • Adding features and improving Timber!!!

Preparing the player (and other sprites)

Let's add the code for the player's sprite as well as a few more sprites and textures at the same time. The following, quite large, block of code also adds a gravestone sprite for when the player gets squashed, an axe sprite to chop with, and a log sprite that can whiz away each time the player chops.

Notice that, after the spritePlayer object, we declare a side variable, playerSide, to keep track of where the player is currently standing. Furthermore, we add some extra variables for the spriteLog object, including logSpeedX, logSpeedY, and logActive, to store how fast the log will move and whether it is currently moving. The spriteAxe also has two related float constant variables to remember where the ideal pixel position is on both the left and the right.

Add the following block of code just before the while(window.isOpen()) code, like we have done so often before. Note that all of the code in the following block is new, not...

Drawing the player and other sprites

Before we add the code to move the player and use all of our new sprites, let's draw them. We are doing it this way so that as we add code to update/change/move them, we will be able to see what is happening.

Add the following highlighted code to draw the four new sprites:

// Draw the tree
window.draw(spriteTree);
// Draw the player
window.draw(spritePlayer);
// Draw the axe
window.draw(spriteAxe);
// Draw the flying log
window.draw(spriteLog);
// Draw the gravestone
window.draw(spriteRIP);
// Draw the bee
window.draw(spriteBee);

The preceding code passes our four new sprites, one after the other, to the draw function.

Run the game and you will see our new sprites in the scene:

We are really close to a working game now. The next task is to write some code to allow the player to control what happens.

Handling the player's input

A few different things depend on the movement of the player, as follows:

  • When to show the axe
  • When to begin animating the log
  • When to move all of the branches down

Therefore, it makes sense to set up keyboard handling for the player who's chopping. Once this is done, we can put all of the features we just mentioned into the same part of the code.

Let's think for a moment about how we detect keyboard presses. Each frame, we test whether a particular keyboard key is currently being held down. If it is, we take action. If the Esc key is being held down, we quit the game, and if the Enter key is being held down, we restart the game. So far, this has been sufficient for our needs.

There is, however, a problem with this approach when we try and handle the chopping of the tree. The problem has always been there; it just didn't matter until now. Depending on how powerful your PC is, the game loop could be executing...

Handling death

Every game must end badly with either the player running out of time (which we have already handled) or getting squashed by a branch.

Detecting the player getting squashed is really simple. All we want to know is: does the last branch in the branchPositions array equal playerSide? If it does, the player is dead.

Add the following highlighted code that detects and executes when the player is squashed by a branch. We will talk about it later:

    // Handle a flying log
    if (logActive)
    {
        spriteLog.setPosition(
            spriteLog.getPosition().x + 
                (logSpeedX * dt.asSeconds()),
            
       &...

Simple sound FX

In this section, we will add three sounds. Each sound will be played on a particular game event, that is, a simple thud sound whenever the player chops, a gloomy losing sound when the player runs out of time, and a retro crushing sound when the player is squashed to death.

How SFML sound works

SFML plays sound effects using two different classes. The first class is the SoundBuffer class. This is the class that holds the actual audio data from the sound file. It is SoundBuffer that is responsible for loading the .wav files into the PC's RAM in a format that can be played without any further decoding work.

When we write code for the sound effects in a minute, we will see that, once we have a SoundBuffer object with our sound stored in it, we will then create another object of the Sound type. We can then associate this Sound object with a SoundBuffer object. Then, at the appropriate moment in our code, we will be able to call the play function of the appropriate...

Improving the game and the code

Take a look at these suggested enhancements for the Timber!!! project. You can see the enhancements in action in the Runnable folder of the download bundle:

  • Speed up the code: There is a part of our code that is slowing down our game. It doesn't matter for this simple game, but we can speed things up by putting the sstream code in a block that only executes occasionally. After all, we don't need to update the score thousands of times a second!
  • Debugging console: Let's add some more text so that we can see the current frame rate. Like the score, we don't need to update this too often. Once every hundred frames will do.
  • Add more trees to the background: Simply add some more tree sprites and draw them in whatever position looks good (some nearer the camera and some further away).
  • Improve the visibility of the HUD text: We can draw simple RectangleShape objects behind the score and the FPS counter. Black with a bit...

Summary

In this chapter, we added the finishing touches and graphics to the Timber!!! game. If, prior to this book, you had never coded a single line of C++, then you can give yourself a big pat on the back. In just five modest chapters, you have gone from zero knowledge to a working game.

However, we will not be congratulating ourselves for too long because, in the next chapter, we will move straight on to some slightly more hardcore C++. While the next game, a simple Pong game, in some ways is simpler than Timber!!, learning about writing our own classes will prepare us for building more complicated and fuller-featured games.

FAQ

Q) I admit that the arrays solution for the clouds was more efficient. But do we really need three separate arrays—one for active, one for speed, and one for the sprite itself?

A) If we look at the properties/variables that various objects have, for example, Sprite objects, we will see they are numerous. Sprites have position, color, size, rotation, and more as well. But it would be just perfect if they had active, speed, and perhaps some more. The problem is that the coders at SFML can't possibly predict all of the ways that we will want to use their Sprite class. Fortunately, we can make our own classes. We could make a class called Cloud that has a Boolean for active and int for speed. We can even give our Cloud class an SFML Sprite object. We could then simplify our cloud code even further. We will look at designing our own classes in the next chapter.

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}