Reader small image

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

Product typeBook
Published inMar 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781800565869
Edition3rd Edition
Languages
Right arrow
Author (1)
John Horton
John Horton
author image
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 about John Horton

Right arrow

Chapter 19: Listening with the Observer Pattern, Multitouch, and Building a Particle System

In this chapter, we will get to code and use our first design pattern. The Observer pattern is exactly what it sounds like. We will code some classes that will indeed observe another class. We will use this pattern to allow the GameEngine class to inform other classes when they need to handle user input. This way, individual classes can handle different aspects of user input.

In addition, we will code a particle system. A particle system comprises hundreds or even thousands of graphical objects that are used to create a visual effect. Our particle system will look like an explosion.

Here is a summary of the topics that will be covered in this chapter:

  • The Observer pattern
  • Upgrading the player's controls to handle multitouch inputs
  • Using the Observer pattern for a multitouch UI controller to listen for broadcasts from the game engine
  • Implementing a particle system...

The Observer pattern

What we need is a way for the GameEngine class to send touch data to the UIController class, which we will code later in this chapter, and then (in the next chapter) to the PlayerController class. We need to separate responsibility for different parts of touch handling because we want UIController and PlayerController to be responsible for handling the aspects of control related to them. This makes sense. UIController knows all about the UI and how to respond, while PlayerController knows all about controlling the player's spaceship. Putting the GameEngine class in charge of all such things is bad encapsulation and very hard to achieve anyway.

In the first three projects, our main game engine-like class did handle all the touch data, but the price of that was that each and every object was declared and managed from the game engine-like class. We don't want to do it like that this time. We are moving on to a better encapsulated place. In the Snake...

Coding the Observer pattern in Scrolling Shooter

Now that we are well versed on how the Observer pattern works, and we have had a good look at the interfaces we will need to write, and how they will be used, we can put all the theory into practice in the Scrolling Shooter project.

As the specific use for our broadcaster and observers is to handle the player's input, we will code a class to handle the screen touches for the HUD. As a reminder, the GameEngine class will be a Broadcaster, and the two separate classes that handle user input will be Observers. As the HUD and the player's spaceship are very different things, it makes sense for each of them to handle their own input.

We will code the UIController class, which will be our first observer (for the HUD play/pause button) in this section and later in the project, we will code our second observer to handle the spaceship controls.

Tip

As we have learned, there is nothing stopping us adding more observers or...

Coding a multitouch UI controller and making it a listener

Create a new Java class and call it UIController.

Tip

As already stated, later in the project, we will also have another InputObserver instance based around the player spaceship game object, but we need to do a bit more theory in the next chapter before we can implement that.

Add some class imports along with the implements InputObserver code to the class declaration and make the class a package. Also, add the constructor, as highlighted next:

import android.graphics.Point;
import android.graphics.Rect;
import android.view.MotionEvent;
import java.util.ArrayList;
class UIController implements InputObserver {
    public UIController(GameEngineBroadcaster b){
        b.addObserver(this);
    }
}

All we need to do in the constructor is call the addObserver method using the GameEngineBroadcaster instance, b, that was passed in as a parameter...

Running the game

Run the game. You can tap the start/pause/resume button to start the game (the button in the top-right corner):

Figure 19.2 – Running the game

Figure 19.2 – Running the game

When the game is running, you can also use the start/pause/resume button to flip between the paused and running states. Obviously, nothing significant happens yet when it's running, but we will change this next.

Implementing a particle system explosion

A particle system is a system that controls particles. In our case, ParticleSystem is a class that will spawn instances (lots of instances) of the Particle class that will create a simple explosion effect. Here is an image of the particles controlled by the particle system as it will appear by the end of this chapter:

Figure 19.3 – Particle system explosion

Important note

The particle system in the finished game is plain white with smaller particles. By the end of this chapter, it will be explained how to achieve both types of particle and you can then choose. The smaller plain white particle suits the game better (in my opinion), but the big multi-colored particles show up better in the pages of a book.

Just for clarification, each of the colored squares is an instance of the Particle class, and all the Particle instances are controlled and held by the ParticleSystem class.

We will start by coding the...

Building a physics engine to get things moving

Create a new class called PhysicsEngine and edit it to match the following code:

class PhysicsEngine {
   // This signature and much more will 
//change later in the project
   boolean update(long fps, ParticleSystem ps){
        
        if(ps.mIsRunning){
            ps.update(fps);
        }
        return false;
    }
   // Collision detection method will go here
}

The PhysicsEngine class only has one method for now – update. By the end of the project, it will have another method for checking collisions. The signature of the update method receives the frames per second and a ParticleSystem instance. The code simply checks whether ParticleSystem...

Running the game

Now you can run the game, tap on the screen, tap the play/pause button, and then the ParticleSystem class will burst into action:

Figure 19.5 – Running the game

Quite spectacular for half an hour's work! In fact, you will probably want to reduce the number of particles to fewer than 100, perhaps make them all white, and maybe reduce their size as well. All these things you can easily do by looking at the ParticleSystem class and its comments.

Tip

The screenshot of the particle explosion at the start of the previous chapter was with fewer, smaller, and just white particles.

Delete this temporary code from the onTouchEvent method of the GameEngine class:

// This is temporary code to emit a particle system
mParticleSystem.emitParticles(
            new PointF(500,500));

Soon, we will spawn our particle system from the physics engine when one of our lasers hits...

Summary

We have covered a lot of ground in this chapter. We have learned a pattern called the Observer pattern, and that one class is a broadcaster while other classes called observers can register with the broadcaster and receive updates. We used the Observer pattern to implement the first part of the user input by handling the play/pause button. We added a bit of action to the chapter when we also coded a ParticleSystem class ready to spawn an explosion whenever the player destroys an enemy ship.

In the next chapter, we will learn other useful programming patterns, including one called the Entity-Component pattern and another called the Factory pattern. We will use them to code and build the player's ship, which will be able to shoot rapid fire lasers and will be able to zoom around with a city skyline scrolling smoothly in the background.

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 2021Publisher: PacktISBN-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.
undefined
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

Author (1)

author image
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 about John Horton