Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Android Game Programming By Example
Android Game Programming By Example

Android Game Programming By Example: Harness the power of the Android SDK by building three immersive and captivating games

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Android Game Programming By Example

Chapter 2. Tappy Defender – First Step

Welcome to the first game, which we will learn about in three chapters. In this chapter, we will closely examine the goals for the finished product. It helps a lot when building a game, if we know exactly what we are trying to achieve.

We can then look at the structure of our code, including an approximate design pattern that we will be adhering to. Then, we will put together the code skeleton of our first game engine. Finally, to finish the chapter, we will draw our first real object from the game and animate it on the screen.

We will then be ready for Chapter 3, Tappy Defender – Taking Flight, where we can make really fast progress before completing our first game in Chapter 4, Tappy Defender – Going Home.

Planning the first game

In this section, we will flesh out exactly what our game will be. The backstory; who is our hero and what are they trying to achieve? The game mechanics; what will the player actually do? What buttons will he press and in what way is that a challenge or fun thing to do? Then, we will look at the rules. What constitutes victory, death, and progress? Finally, we will get technical and start to examine how we will actually build the game.

Backstory

Valerie has been defending the far outposts of humanity since the early '80s. Her brave exploits were originally immortalized in the 1981 arcade classic, Defender. However, after over 30 years on the front line, she is retiring and it is time to begin the journey home. Unfortunately, in a recent skirmish, her ship's engines and navigation systems were severely damaged. Therefore, now she must fly all the way home using only her boost thruster.

This means that she must fly her ship by simultaneously thrusting up and...

Building the home screen

Since we have done all the planning and preparation, we can get started with the code.

Note

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

To use the code files, you will still need to create an Android Studio project. In addition, you will need to change the package name in the very first line of code of each of the JAVA files. Change the package name to match the package name of the project you created. Finally, you will need to make sure that any assets such as images or sound files are placed into the appropriate folder in the project. All the required assets for each project are supplied in the download bundle.

Creating the project

Fire up Android Studio and create a new project by following these steps...

Coding the game loop

We said that we will not be using a UI layout for our game screen, but instead a dynamically drawn view. This is where the view of our pattern comes in. Let's create a new class to represent our view, then we will put in the fundamental building blocks of our Tappy Defender game.

Building the view

We will leave our two activity classes alone for a while so that we can take a look at our class that will represent the view of our game. As we discussed at the start of this chapter, the view and the controller aspects will be part of the same class.

The Android API provides us with an ideal class for our requirements. The android.view.SurfaceView class not only provides us a view that is designed for drawing pixels, text, lines, and sprites onto, but also enables us to quickly handle player input as well.

As if this wasn't useful enough, we can also spawn a thread by implementing the runnable interface allowing our main game loop to get player input and other system...

The PlayerShip object

We need to keep the model part of our code as separate as possible from the rest. We can do this by creating a class for our player's spaceship. Let's call our new class PlayerShip.

Go ahead and add a new class to the project, and call it PlayerShip. Here are a few quick steps on how to do that. Now, right-click the folder with our .java files in it and navigate to New | Java Class, then enter PlayerShip as the name and click on OK.

What do we need our PlayerShip class to be able to know about itself? As a bare minimum it needs to:

  • Know where it is on the screen
  • What it looks like
  • How fast it is flying

These requirements suggest a few member variables we can declare. Enter the code just after the class declaration that we generated:

private Bitmap bitmap;
private int x, y;
private int speed = 0;

As usual, use the Alt | Enter keyboard combination to import any missing classes. In the previous block of code, we see that we have declared an object of type Bitmap that...

Drawing the scene

As we will see, drawing a bitmap is really trivial. But the coordinate system that we use to draw our graphics onto needs a brief explanation.

Plotting and drawing

When we draw a Bitmap object to the screen, we pass in the coordinates we want to draw the object at. The available coordinates of a given Android device depend on the resolution of its screen.

For example, the Samsung Galaxy S4 phone has a screen resolution of 1920 pixels (across) by 1080 pixels (down) when held in a landscape view.

The numbering system of these coordinates starts in the top-left hand corner at 0,0 and proceeds down and to the right until the bottom right corner is pixel 1919, 1079. The apparent 1 pixel disparity between 1920/ 1919 and 1080/ 1079 is because the numbering starts at 0.

Therefore, when we draw a bitmap or any other drawable to the screen, we must specify x, y coordinates.

Furthermore, a bitmap is, of course, comprised of many pixels. So which pixel of a given bitmap is drawn at the...

Deploying the game

Now, we can run our game to see our spaceship floating through space (starting at 50 pixels on the x axis and 50 pixels on the y axis).

Android Studio enables us to fairly quickly create emulators, on which we can test our games on a development PC. However, even the most simple of games will not run well on an emulator. When we start testing things like player input, the experience is so awful that it is best to avoid using emulators completely.

The solution is to carry out debugging on a real Android device. It is very easy to prepare for this.

Debugging on an Android device

The first thing to do is to visit your device manufacturer's website and obtain and install any drivers that are required for your device and operating system.

The next few steps will setup the Android device for debugging. Note that different manufacturers structure the menu options slightly differently than others. The following sequence is probably very close, if not exact to enable debugging...

Planning the first game


In this section, we will flesh out exactly what our game will be. The backstory; who is our hero and what are they trying to achieve? The game mechanics; what will the player actually do? What buttons will he press and in what way is that a challenge or fun thing to do? Then, we will look at the rules. What constitutes victory, death, and progress? Finally, we will get technical and start to examine how we will actually build the game.

Backstory

Valerie has been defending the far outposts of humanity since the early '80s. Her brave exploits were originally immortalized in the 1981 arcade classic, Defender. However, after over 30 years on the front line, she is retiring and it is time to begin the journey home. Unfortunately, in a recent skirmish, her ship's engines and navigation systems were severely damaged. Therefore, now she must fly all the way home using only her boost thruster.

This means that she must fly her ship by simultaneously thrusting up and forward,...

Left arrow icon Right arrow icon

Description

The book is best suited for existing Android or Java programmers who want to adapt their skills to make exciting Android games. The book is also for determined readers who might have no Android, game programming or even Java experience, but a reasonable understanding of object oriented programming knowledge is assumed.

What you will learn

  • Build simple to advanced game engines for different types of game, with cool features such as sprite sheet character animation and scrolling parallax backgrounds
  • Design and implement genuinely challenging and playable levels
  • Implement the critical main game loop
  • Implement basic and advanced collision detection mechanics
  • Bring to life a challenging enemy AI
  • Make the math behind 2D rotation, velocity, and collisions simple
  • Run your game designs at 60 frames per second or better
  • Process multitouch screen input effectively and efficiently
  • Implement a multitude of other game features such as pickups, firing weapons, HUDs, generating and playing sound FX, scenery, level transition, high scores, and more
  • Implement a flexible and advanced game engine that uses OpenGL ES 2 for fast, smooth frame rates

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 30, 2015
Length: 388 pages
Edition : 1st
Language : English
ISBN-13 : 9781785280122
Vendor :
Google
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jun 30, 2015
Length: 388 pages
Edition : 1st
Language : English
ISBN-13 : 9781785280122
Vendor :
Google
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 115.97
Android Game Programming By Example
€36.99
Learning Java by Building Android Games
€36.99
Android NDK Beginner`s Guide - Second Edition
€41.99
Total 115.97 Stars icon

Table of Contents

12 Chapters
1. Player 1 UP Chevron down icon Chevron up icon
2. Tappy Defender – First Step Chevron down icon Chevron up icon
3. Tappy Defender – Taking Flight Chevron down icon Chevron up icon
4. Tappy Defender – Going Home Chevron down icon Chevron up icon
5. Platformer – Upgrading the Game Engine Chevron down icon Chevron up icon
6. Platformer – Bob, Beeps, and Bumps Chevron down icon Chevron up icon
7. Platformer – Guns, Life, Money, and the Enemy Chevron down icon Chevron up icon
8. Platformer – Putting It All Together Chevron down icon Chevron up icon
9. Asteroids at 60 FPS with OpenGL ES 2 Chevron down icon Chevron up icon
10. Move and Draw with OpenGL ES 2 Chevron down icon Chevron up icon
11. Things That Go Bump – Part II Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(9 Ratings)
5 star 66.7%
4 star 11.1%
3 star 22.2%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Rodger Jan 06, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
John Horton describes exactly how to write for Android and Java without throwing masses of unintelligible buzzwords at you. Each stage is carefully and easily explained and each new concept and word is explained in plain english. This does not mean that he doesn't teach in depth but only that he introduces the ideas as you need them to understand what you are doing. I have read and tried to follow many books and videos on android and John Hortons books have taught me more than any of the others.
Amazon Verified review Amazon
Guillermo Rodriguez Jul 17, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is excellent! It has a fresh, fun style, but at the same time it covers the topics of Android Game Development with technical depth and correctness It is a wonderful tool for every Android programmer.
Amazon Verified review Amazon
Hugo Oct 14, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I think the title is wrong, this isn't just a programming book, this is a complete game development course, the author starts by talking about what you will have at the end, them he introduces every game talking about the foundations not just code and result, you are introduced to good practices to achieve your game complete, it is fundamental in my opinion to have a project complete, the programming part is really good as he is presenting the critical points of the game structure in natural basis, you understand what he does because you understand the need of that code part. I think that the difficult of this book is between intermediate to advanced, but he made a book that everyone who wants to make a mobile game can start with solid basis. All the projects has its own focus and difficult level, I think they shown almost every feature you need to make a good 2d mobile game.
Amazon Verified review Amazon
jamie Jul 30, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Fantastic book and i would give 10 stars if possible! i have to disagree with another review i have seen about the book not being useful to developers at beginner level, although the book intro does assume you have some development knowledge it all depends on what you are looking to take from this book! i am practically new to android game development and needed to know more on game loops and sprites and i got this know how by reading this book and putting it to practice with the games made in this book so even from a beginners point of view i have to say that what i have took from this book has been a massive help towards my understanding of what it takes to get games built and running! java code in any book anywhere can seem daunting to all of us but by using examples i find it is the best method and by example is exactly what this book shows, if you still do not get whats happening in code then simply go over it again as with everything in life, things become clearer the more you practice.Before i read and used the examples in this book i was at a stand still with my games development and was annoyed with my self as was trying to take so much information in from a number of different sources it was really taking a toll on me but when i came accross this book it ticked all the right boxes and i am glad i gave my time to read this as all this time it was one source i really needed to focus on with the right information and it happend to be the best choice i made investing my time into this because it gave me everything i needed to know and more! i am now confident with my own looping and sprites, and much better ways of the headach i was having with fps, this book is not just good to give a once over! for me it is also an ideal reference book.The way the book has been written is very straight forward and informative this makes it easy to follow, you can copy and paste the code or download the code if you have a paperback copy however if your new to development and really keen to learn i find that by writing the code myself gives me that bit extra of my learning progress and comes across clearer then copy and pasting chunks of code.I hope this book helps you all as much as it has helped me, if your really serious about android games development then you can never have enough learning books, i do highly recommend to add this to your front collection.thank you to John Horton and also to Packt for this book being here today! i had almost given up so for this i am truly thankful and will look out for more books from you in the future should there be any.Jamie LoweGames Developer in the making.
Amazon Verified review Amazon
Thomas Möller Aug 15, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Der Autor erläutert die Spieleprogrammierung auf Android-Geräten anhand von drei 2D-Spielen. Diese Rezension bezieht sich nur auf die ersten beiden Spiele. Das dritte Spiel (Asteroids mit Nutzung von OpenGL ES 2) habe ich bisher noch nicht durchgearbeitet.John Horton nutzt für die Spieleprogrammierung keine UI-Elemente des Android Betriebssystem (wie z.B. Button, Layout, Textfields usw.) und benötigt daher keinen Rückgriff auf die mit den Activities assozierten XML-Dateien. Daher braucht man keine weiteren Kenntnisse über die Android-UI-Bibliotheken, was recht entspannend ist.Alles wird im Android-Canvas (eine Art Leinwand, die später im Spiel die Displayanzeige darstellt) direkt in Java programmiert.Der Autor entwickelt im ersten Spiel eine Game-Engine, die gut funktioniert und sich auch leicht auf eigene Spielideen übertragen lässt.Im zweiten Spiel (Run & Jump) wird die Game-Engine dann erweitert und verwaltet zahlreiche Grafikobjekte, mit denen der Spieler auf verschiedene Weise interagiert. Dazu kommt noch ein mehrstufig scollender Hintergrund, der dadurch sogar eine räumliche Tiefe des Hintergrunds erzielt. Das Spiel wird von Anfang an so programmiert, dass es einen Level-Editor enthält, mit dem ohne größere Eingriffe in das Javaprogramm eigene Levels erstellt und beliebig geändert werden können. Dazu reicht ein einfacher Texteditor aus. Die neuen oder geänderten Level müssen lediglich in das Programm eingebunden werden, was aber mit wenigen Programmzeilen möglich ist.John Horton erklärt recht kleinschrittig die einzelnen Programmschritte. Ich fand sie dadurch gut nachvollziehbar. Ein Spiel erstreckt sich über mehrere Buchkapitel. Mindestens am Ende jedes Kapitels, häufig aber auch zwischendurch, werden Teilabschnitte der Programmierung fertiggestellt, die ein Testen des Spiels zulassen. So bleibt die Motivation hoch und man kann schnell die Wirkung der Programmteile erkunden.Pro: - Gut verständlich, sofern man Javakenntnisse besitzt. - Motivierende und grafisch schon recht anspruchsvolle Spiele (zumindest das 2. Spiel). - Gut strukturierte Programmierung durch Nutzung von Vererbung, MVC-Architektur (zumindest soweit sinnvoll) und Datenkapselung. - Der Autor erläutert meistens recht genau, wo jeweils die neuen Codezeilen in den Klassen programmiert werden müssen, so dass man auch ohne Downloads der Source-Dateien das Programm nach und nach selbst eintippen kann. - Am Ende jedes Spiels zeigt der Autor noch einige Ideen auf, wie das Spiel ohne großen Programmieraufwand erweitert und verbessert werden kann. Dazu können in der Regel die bisher geschaffenen Programmelemente genutzt werden oder müssen nur geringfügig erweitert werden.Contra: - Das Layout der Codezeilen ist teilweise schlecht formatiert. Es sind z.T. Einrückungen vorhanden, wo keine hingehören und umgekehrt. Das erschwert das Lesen und Verstehen des Codes etwas. - Im zweiten (und schon recht komplexen Spiel) wollte der Autor wohl mit den letzten Programmteilen schnell (oder endlich) fertig werden. Leider enthalten dort zwei Klassen bzw. umfangreichere Methoden Fehler (keine bloßen Flüchtigkeitsfehler). Sie fallen bei einem Kurztest möglicherweise nicht aber bei etwas längeren Tests oder geändertem Level schon. Sofern man aber bis dahin den Erklärungen folgen konnte, ist man auch in der Lage, die Programme entsprechend zu ändern, obwohl die notwendigen Änderungen jeweils recht umfangreich waren.Trotz dieser eher kleinen Abstriche steckt das Buch aber so voller Ideen und hilfreicher Konzepte, dass es für mich sehr wertvoll ist und 5 Sterne verdient. Ich freue mich schon auf die Erläuterungen für das dritte und letzte Spiel (welches w.o. erwähnt sogar OpenGL ES 2 nutzt).Für den Leser sind moderate Java-Kenntnisse erforderlich, Android-Kenntnisse dagegen kaum.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.