Reader small image

You're reading from  Android Game Programming by Example

Product typeBook
Published inJun 2015
Reading LevelIntermediate
Publisher
ISBN-139781785280122
Edition1st Edition
Languages
Tools
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 9. Asteroids at 60 FPS with OpenGL ES 2

Welcome to the final project. Over the course of the next three chapters, we will build an Asteroids-like game using the OpenGL ES 2 graphics API. If you are wondering exactly what OpenGL ES 2 is, then we will discuss the details later in this chapter.

We will build a very simple but fun and challenging game, where we can draw and animate hundreds of objects at a time, even on quite old Android devices.

With OpenGL, we will take our drawing efficiency to a much higher level, and with some not-too-tricky math, our movement and collision detection will be greatly enhanced compared to our previous projects.

By the end of this chapter, we will have a basic working OpenGL ES 2 engine drawing our simple but temporarily static spaceship to the screen; at 60 FPS or higher.

Tip

If you have never seen or played the '80s arcade hit (released in November 1979) Asteroids, why not go and check out a clone of it or a video now?

Free web game at http://www.freeasteroids...

Asteroids simulator


Our game will be set in a four directional scrolling world that the player will be able to traverse while hunting for asteroids. The world will be enclosed in a rectangular border to keep the asteroids from drifting off too far, and the border will also serve as another hazard for the player to avoid.

The game controls

We will reuse our InputController class with a few simple modifications and can even keep the same button layout. As we will see, however, we will draw the buttons on screen in a very different manner to our retro platformer. Also, instead of walking left and right, the player will rotate the ship left and right through 360 degrees. The jump button will become a thrust toggle switch to turn on and off forward motion, and the shoot button will remain just that. We will also have the pause button in the same place.

Rules for the game

When an asteroid hits the border, it will bounce back into the game world. If the player hits the border, a life will be lost and...

Introducing OpenGL ES 2


OpenGL ES 2 is the second major version of the Open Graphics Library (OpenGL) for embedded systems. It is the mobile incarnation of OpenGL for desktop systems.

Why use it and how does it work?

OpenGL runs as a native process, not on the Dalvik virtual machine like the rest of our Java. This is one of the reasons it is super fast. The OpenGL ES API takes away all of the complexity of interacting with native code, and OpenGL itself also provides very efficient and fast algorithms within its native code base.

The first version of OpenGL was completed in 1992. The point is that even back then OpenGL used arguably the most efficient code and algorithms to draw graphics. Now, more than 20 years on, it has been continually refined and improved as well as adapted to work with the latest graphics hardware, both mobile and desktop. All the mobile GPU manufacturers specifically design their hardware to be compatible with the latest version of OpenGL ES.

Trying to improve on OpenGL...

Preparing OpenGL ES 2


First we start off with our Activity class, which as before is the entry point into our game. Create a new project and in the Application Name field enter C9 Asteroids. Choose Phones and tablets, then Blank Activity when prompted. In the Activity Name field type AsteroidsActivity.

Tip

Obviously you don't have to follow my exact naming choices but just remember to make the minor alterations in code to reflect your own naming choices.

You can delete activity_asteroids.xml from the layout folder. You can also delete all the code within the AsteroidsActivity.java file. Just leave the package declaration.

Locking the layout to landscape

Just as we did for the previous two projects, we will make sure the game runs in landscape mode only. We will make our AndroidManifest.xml file, force our AsteroidsActivity class to run with a full screen, and lock it to a landscape orientation. Let's make these changes:

  1. Open the manifests folder now and double-click the AndroidManifest.xml file...

Building an OpenGL-friendly, GameObject super class


Let's dive straight into the code. As we will see, this GameObject will have a lot in common with the GameObject class from the previous project. The most significant difference will be that this latest GameObject will of course draw itself using a handle to the GL program, primitive (vertex) data from a child class, and the viewport matrix contained in viewportMatrix.

Create a new class, call it GameObject, and enter these import statements, noting again that that some of them are static:

import android.graphics.PointF;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import static android.opengl.GLES20.GL_FLOAT;
import static android.opengl.GLES20.GL_LINES;
import static android.opengl.GLES20.GL_POINTS;
import static android.opengl.GLES20.GL_TRIANGLES;
import static android.opengl.GLES20.glDrawArrays;
import static android.opengl.GLES20.glEnableVertexAttribArray;
import static android.opengl.GLES20.glGetAttribLocation...

The spaceship


This class is nice and simple, although it will evolve with the project. The constructor receives the starting location within the game world. We set the ship's type and world location using the methods from the GameObject class, and we set a width and height.

We declare and initialize some variables to simplify the initialization of the model space coordinates, and then we go ahead and initialize a float array with three vertices that represent the triangle that is our ship. Note that the values are based around a center of x = 0 and y = 0.

All we do next is, call setVertices(), and GameObject will prepare the ByteBuffer ready for OpenGL:

public class SpaceShip extends GameObject{

  public SpaceShip(float worldLocationX, float worldLocationY){
       super();

        // Make sure we know this object is a ship
        // So the draw() method knows what type
        // of primitive to construct from the vertices

        setType(Type.SHIP);

        setWorldLocation(worldLocationX...

Drawing at 60 + FPS


In three simple steps, we will be able to glimpse our spaceship:

  • Add a SpaceShip object to the GameManager member variables:

    private boolean playing = false;
    
      // Our first game object
         SpaceShip ship;
    
         int screenWidth;
  • Add a call to the new SpaceShip() to the createObjects method:

    private void createObjects() {
            
      // Create our game objects
      // First the ship in the center of the map
         gm.ship = new SpaceShip(gm.mapWidth / 2, gm.mapHeight / 2);
    }
  • Add the call to draw the spaceship in each frame in the draw method of AsteroidsRenderer:

    // Start drawing!
    // Draw the ship
    gm.ship.draw(viewportMatrix);
    

Run the game and see the output:

Not exactly impressive visuals, but it is running between 67 and 212 frames per second in debug mode while outputting to the console on an ageing Samsung Galaxy S2 phone.

It will be our aim throughout the project to add hundreds of objects and keep the frames per second over 60.

Tip

One of the book's reviewers reported frame rates...

Summary


Setting up a drawing system was a little bit long-winded. However, now that it is done, we can churn out new objects much more easily. All we have to do is define the type and the vertices, then we can draw them with ease.

It is because of this ground work that the next chapter will be much more visually rewarding. Next, we will create blinking stars, a game world border, spinning and moving asteroids, whizzing bullets, and a HUD, as well as add full controls and motion to the spaceship.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Game Programming by Example
Published in: Jun 2015Publisher: ISBN-13: 9781785280122
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