Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning Java by Building Android Games - Third Edition

You're reading from  Learning Java by Building Android Games - Third Edition

Product type Book
Published in Mar 2021
Publisher Packt
ISBN-13 9781800565869
Pages 686 pages
Edition 3rd Edition
Languages
Author (1):
John Horton John Horton
Profile icon John Horton

Table of Contents (24) Chapters

Preface 1. Chapter 1: Java, Android, and Game Development 2. Chapter 2: Java – First Contact 3. Chapter 3: Variables, Operators, and Expressions 4. Chapter 4: Structuring Code with Java Methods 5. Chapter 5: The Android Canvas Class – Drawing to the Screen 6. Chapter 6: Repeating Blocks of Code with Loops 7. Chapter 7: Making Decisions with Java If, Else, and Switch 8. Chapter 8: Object-Oriented Programming 9. Chapter 9: The Game Engine, Threads, and the Game Loop 10. Chapter 10: Coding the Bat and Ball 11. Chapter 11: Collisions, Sound Effects, and Supporting Different Versions of Android 12. Chapter 12: Handling Lots of Data with Arrays 13. Chapter 13: Bitmap Graphics and Measuring Time 14. Chapter 14: Java Collections, the Stack, the Heap, and the Garbage Collector 15. Chapter 15: Android Localization – Hola! 16. Chapter 16: Collections and Enumerations 17. Chapter 17: Manipulating Bitmaps and Coding the Snake Class 18. Chapter 18: Introduction to Design Patterns and Much More! 19. Chapter 19: Listening with the Observer Pattern, Multitouch, and Building a Particle System 20. Chapter 20: More Patterns, a Scrolling Background, and Building the Player's Ship 21. Chapter 21: Completing the Scrolling Shooter Game 22. Chapter 22: What Next? 23. Other Books You May Enjoy

Chapter 11: Collisions, Sound Effects, and Supporting Different Versions of Android

By the end of this chapter, we will have a fully working and beeping implementation of the Pong game. We will start the chapter off by looking at some collision detection theory, which will be put into practice toward the end of the chapter. We will also learn how we can detect and handle different versions of Android. We will then be in a position to study the SoundPool class and the different ways we use it depending on the Android version the game is running on. At this point, we can then put everything we have learned into producing some more code to get the Pong ball bouncing and beeping as well as put the finishing touches to the game.

In summary, we will cover the following topics:

  • Studying the different types of collision detection
  • Learning how to handle different versions of Android
  • Learning how to use the Android SoundPool class
  • Finishing the Pong game

Mind your...

Handling collisions

As collision detection is something that we will need to implement in all the remaining projects in this book, I thought a broader discussion beyond what is required for Pong might be useful. Furthermore, I am going to use some images from the fifth game project to visually demonstrate some topics around collision detection.

Collision detection is quite a broad subject, so here is a quick look at our options for collision detection and in which circumstances different methods might be appropriate.

Essentially, we just need to know when certain objects from our game touch other objects. We can then respond to that event by bouncing the ball, adding to the score, playing a sound, or whatever is appropriate. We need a broad understanding of our different options, so we can make the right decisions in any particular game.

Collision detection options

First, here are a few of the different ways we can use mathematics to detect collisions, how we can utilize...

Handling different versions of Android

Most of the time throughout this book we haven't paid any attention to supporting older Android devices. The main reason for this is that all the up-to-date parts of the API we have been using work on such a high percentage of devices (in excess of 98%) that it has not seemed worthwhile. Unless you intend to carve out a niche in apps for ancient Android relics, this seems like a sensible approach. Regarding playing sounds, however, there have been some relatively recent modifications to the Android API.

Actually, this isn't immediately a big deal because devices newer than this can still use the old parts of the API. But it is good practice to specifically handle these differences in compatibility, because eventually, one day, the older parts might not work on newer versions of Android.

The main reason for discussing this here and now is that the slight differences in pre- and post-Android Lollipop sound handling gives us a good...

The SoundPool class

The SoundPool class allows us to hold and manipulate a collection of sound effects; literally, a pool of sounds. The class handles everything from decompressing a sound file such as a .wav or .ogg file, keeping an identifying reference to it via an integer ID, and, of course, playing the sound. When the sound is played it is done so in a non-blocking manner (using a thread behind the scenes) that does not interfere with the smooth running of our game or our user's interaction with it.

The first thing we need to do is add the sound effects to a folder called assets in the main folder of the game project. We will do this for real shortly.

Next, in our Java code, we would declare an object of type SoundPool and an int identifier for every sound effect we intend to use. In this theoretical case, we also declare another int called nowPlaying, which we can use to track which sound is currently playing and we will see how we do this shortly:

// create an...

Generating sound effects

There is an open-source app called Bfxr that allows us to make our own sound effects. Here is a very fast guide to making your own sound effects using Bfxr. Grab a free copy from www.bfxr.net. If your operating system isn't supported or if you prefer, you can generate sounds on the website in your web browser.

Tip

Note that the sound effects are supplied to you on the GitHub repo in the Chapter 11/assets folder. You don't have to create your own sound effects unless you want to. It is still worth getting this free software and learning how to use it.

Follow the simple instructions on the website to set it up:

Tip

This is a seriously condensed tutorial. You can do so much with BFXR. To learn more, read the tips on the website at the previous URL.

  1. Try out a few of these things to make cool sound effects. First, run Bfxr:

    Figure 11.6 – Running Bfxr

  2. Try out all the preset types that generate a random sound of that type...

Adding sound to the Pong game

Copy the assets folder and all its contents from the Chapter 11 folder on the GitHub repo. Now use your operating system's file explorer to navigate to the Pong/app/src/main folder of your project. Paste the assets folder and its contents.

Obviously, feel free to replace all the sound effects in the assets folder with your own. If you decide to replace all the sound effects, make sure you name them exactly the same or that you make appropriate edits in the code that follows.

Notice that if you look in the project explorer window in Android Studio, you can view the assets folder and can see that the sound effects have been added to the project:

Figure 11.10 – Viewing the assets folder

Let's write the code.

Adding the sound variables

At the end of the member variable declarations, before the PongGame constructor, add the following code:

// All these are for playing sounds
private SoundPool mSP;
private...

Coding the collision detection and playing sounds

Now that we have done so much theory and preparation, we can finish everything off very quickly. We will write code to detect all the various collisions using the RectF intersects method, play sounds, and call the required methods of our classes.

The bat and the ball

Add the following highlighted code inside the detectCollisions method:

private void detectCollisions(){
     // Has the bat hit the ball?
     if(RectF.intersects(mBat.getRect(), mBall.getRect())) {
          // Realistic-ish bounce
          mBall.batBounce(mBat.getRect());
          mBall.increaseVelocity();
          mScore++;
          mSP.play(mBeepID, 1, 1, 0,...

Playing the game

Obviously, pictures are not very good at showing movement, but here is a screenshot just in case you are reading this book on a train and can't run it for yourself:

Figure 11.11 – Playing the game

Figure 11.11 – Playing the game

At this point, you have enough knowledge to revisit the Sub' Hunter game and add some sound effects should you want to.

Summary

We have done a lot of theory in this chapter – everything from the mathematics of detecting collisions to learning how the RectF class has the intersects method that can handle rectangle intersections for us. We also looked closely at the SoundPool class, including how we can detect which version of Android the player is using and vary our code accordingly. Initializing a SoundPool object also brought us into contact with method chaining, where we can call multiple methods on the same object in a single line of code. Finally, we used all this knowledge to complete the Pong game.

Perhaps the best thing is that now we have all this experience and theory behind us, we will now (starting in the next chapter) be able to quickly complete the next game in just two chapters, at the same time as learning about Java arrays, which will help us to handle lots of data.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Learning Java by Building Android Games - Third Edition
Published in: Mar 2021 Publisher: Packt ISBN-13: 9781800565869
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}