34,79 €
AndEngine is a popular and easy-to-use game framework, best suited for Android game development. After learning the basics of creating an Android game using AndEngine it's time you move beyond the basics to explore further. For this you need to understand the theory behind many of the technologies AndEngine uses.
This book aims to provide all the skills and tools you need to learn more about Android game development using AndEngine.
With this book you will get a quick overview of the basics of AndEngine and Android application development. From there, you will learn how to use 3D models in a 2D scene, render a visual representation of a scene's objects, and create interaction between these objects. You will explore frame-based animations and learn to use skeletal animations.
As the book progresses, you will be guided through exploring all the relevant aspects of rendering graphics with OpenGL ES, generating audio using OpenSL ES and OpenAL, making the best use of Android's network API, implementing anti-aliasing algorithms, shaders, dynamic lighting and much more. With all this, you will be ready to enhance the look and feel of your game with its user interface, sound effects and background music.
After an in-depth study of 2D and 3D worlds and multi-player implementations, you will be a master in AndEngine and Android game development.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 313
Veröffentlichungsjahr: 2015
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: September 2015
Production reference: 1220915
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-114-4
www.packtpub.com
Author
Maya Posch
Reviewers
Harshit Agarwal
Scott Bechtel
John Pericos
Sergio Viudes Carbonell
Commissioning Editor
Kartikey Pandey
Acquisition Editors
Nadeem Bagban
James Jones
Content Development Editor
Susmita Sabat
Technical Editor
Utkarsha S. Kadam
Copy Editor
Vikrant Phadke
Project Coordinator
Suzanne Coutinho
Proofreader
Safis Editing
Indexer
Tejal Daruwale Soni
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
Maya Posch is a largely self-taught developer with a profound interest in anything related to technology and science. Having discovered programming at a young age, she proceeded to learn a variety of languages, including C++, PHP, Java, Ada, and VHDL. She has worked on mobile, desktop, and embedded applications and games. Together with a good friend, she started a software and game development company called Nyanko (http://www.nyanko.ws/) in 2006. Maya currently lives in Germany, where she works on games and other projects, and maintains a number of technology- and science-related blogs.
I would like to express my profound thanks to my best friend, Trevor Purdy, who provided feedback and constructive criticism throughout the process. Also, my gratitude to my other friends. They tolerated my prolonged absence during the writing process.
Harshit Agarwal, an IIT graduate, is currently working as a software developer and engineer at Amazon. He was born in Jhansi, India, and completed his schooling there. He scored above 90 percent in both his high school and board examinations. He cleared the prestigious IIT JEE exam in 2011 with an all-India rank of 1973. He completed his bachelors in computer science and engineering from IIT (BHU) Varanasi in 2015. Harshit secured the first rank in Hackathon, a 24-hour Android application development event organized under the annual college technical fest Technex-2013. As a reward, he was offered an internship at Amazon India during the sophomore year of his graduation.
He has ample technical experience. Owing to his internships, he has had the experience of working for both an established MNC, Amazon, and a leading and fast-growing start-up, Cube26. He was also a teaching assistant for a computer programming course in his undergraduate days. His hobbies include swimming, coin collection, and bike riding.
I am highly indebted to my parents and my friends for their constant motivation and timely help. Their valuable suggestions inspired me to review this book without much difficulty. I express my sincere gratitude and thanks to all those who assisted me directly and indirectly during the course of the review.
John Pericos is a software engineer and IT consultant with a lot of experience in Java web and mobile application development. He has his own IT consulting practice and gaming label company called Bitoxic (http://www.bitoxic.com/). He has more than 10 years of software development experience and more than 4 years of Android development experience. John obtained his degree in the field of computer science from the Victoria University of Wellington, New Zealand. He continues to maintain and develop Android applications. You can find his latest development at http://www.bitoxic.com/.
Sergio Viudes Carbonell is 32 years old. He is a developer from Elche, Spain. He has loved to play video games since childhood (since the time of the ZX Spectrum). He also composes electronic music as a hobby. Then, he started coding and studied computer engineering at the University of Alicante.
Sergio started working as a software and web developer, but what he always wanted to do was create video games. So, he founded Baviux, and now he designs and develops mobile apps and games.
He has worked on these books AndEngine for Android Game Development Cookbook, Learning AndEngine, Mobile Game Design, Mastering Android Game Development, and JavaScript Security.
I would like to thank the author of this book for writing it. Special thanks go to my wife, Estefanía, who encourages and supports me every day.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Building a game for Android is easy, thanks to a multitude of game engines and tools that allow you to quickly get started. This is true for AndEngine as well. If you are reading this text, you have probably already tried your hand at, at least, a basic AndEngine game. After getting started like this, the next questions are: how to move from this game to those wonderful games you have seen elsewhere? How to make those cool animations, lighting, shadows, and other amazing effects? And how to get them with AndEngine?
This book takes you through the many advanced topics you may encounter while making the perfect Android-based game. After explaining the theory behind each technology, it proceeds to show you how to implement it in an AndEngine-based application.
Chapter 1, Setting Up the Project, runs through the basics of setting up an AndEngine-based application, as well as shows you how to configure your development environment.
Chapter 2, Replacing 2D Sprites with 3D Models, illustrates how you can use 3D-mesh-based models with AndEngine, adding further tools to your asset development process. This chapter also provides full sample code to demonstrate how to integrate 3D models into AndEngine's rendering process.
Chapter 3, Physics Engine Integration, demonstrates the use of the Box2D physics add-on for AndEngine and discusses 2D versus 3D physics as well as the use of other physics engines.
Chapter 4, Frame-based Animation Sequences, discusses the various ways of implementing animation using frame-based systems. These are demonstrated using AndEngine-based examples.
Chapter 5, Skeletal Animations, looks at the advanced topic of using skeleton-based animation in order to achieve highly refined animation without exceeding resource budgets.
Chapter 6, Creating 3D Effects in 2D, highlights the differences and similarities between 2D and 3D scenes, and tells you how to achieve 3D effects in a 2D scene.
Chapter 7, Static Lighting, shows the various techniques used to add lighting and shadows to a scene without making any dynamic calculations during runtime, as well as the limitations posed by this approach.
Chapter 8, Dynamic Lighting, balances the advantages of using dynamic lighting and shadows against the disadvantages of its runtime requirements.
Chapter 9, User Interfaces, takes a detailed look at the support available for user interfaces as they exist in AndEngine, as well as the use of native Android widgets in an AndEngine application, for example, for text input.
Chapter 10, Shading, Aliasing, and Resolutions, dives into the complex topic of programming GLSL shaders for OpenGL ES 2.0 and better graphics hardware. This chapter also shows you how to add anti-aliasing using this and other methods. Finally, it looks at how to handle the various resolutions of the Android device that the game will eventually run on.
Chapter 11, Adding Sounds and Effects, explores the topic of music and sound effects in a game, looking at native AndEngine APIs as well as the use of OpenSL ES and OpenAL.
Chapter 12, Building Worlds for Our Project, focuses on the broad topic of world-building, including how to construct and load/unload scenes and the management of resources. It also looks at transitioning between different scenes and the concepts of hierarchies and limitations within a scene.
Chapter 13, Networking and Latency, defines the multitude of choices out there for connecting Android devices with each other via a network as well as Bluetooth, and the implications this has on gameplay experiences. This chapter also looks at the MultiPlayer add-on for AndEngine.
Chapter 14, Adding Custom Functionality, finally looks at how you can expand on the lessons learned in this book through a number of techniques to extend AndEngine's functionality without modifying a single line of its code. It also looks at implementing plugin systems in both Java and native code.
In order to follow along with this book, it is important that you use a computer that is supported by the Android SDK and NDK (running Windows, Mac OS X, or Linux). Both Eclipse with the Android Developer Tool (ADT) plugin and the new Android Studio IDE will work.
Possessing an Android device that supports OpenGL ES 2.0 is also very helpful, although many code samples will likely work on the Android SDK's emulator as well.
This book is aimed at developers who have gone through all the basic AndEngine tutorials and books and are looking for something more. It's also very suitable for developers with a lot of knowledge of other game engines who are looking to develop games with AndEngine. Knowledge of Java, C++, and Android development is a prerequisite for getting the most out of this book.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
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.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Before you learn the advanced techniques covered in this book, you first need something to work with—a project that you can use as a foundation to implement every new piece of logic and algorithm. To this end, we will use this first chapter to set up the basis for the AndEngine-based application that we will build throughout the following chapters. We will also cover the basics of Android development, in both Java code and native C/C++, and see how to run and debug the resulting applications.
In this chapter, we will cover these topics:
For this chapter, it is assumed that you have at least basic experience with developing Android applications. Experience with either Eclipse/ADT or Android Studio is useful, as is basic knowledge of coordinate systems and OpenGL.
To quickly set up an AndEngine application, we follow the general procedure of pulling the current AndEngine code from the AndEngine GitHub repository and using it as a library project dependency in our project. We will be using the GLES2-AnchorCenter branch for our project because it's the most current development branch at the time of writing this book. An additional advantage of using the AnchorCenter branch is the main change from the GLES2 branch—it uses the same coordinate system as OpenGL, in the sense that the origin is in the bottom-left part of the screen. This will make our lives easier later on, as it will save us the trouble of having to convert between two different coordinate systems.
Another difference between GLES2 and AnchorCenter is that the former positions new objects by default with the corner as the anchor point, while in the latter's case, the default anchor point is at the center of the object. We can change the anchor point wherever needed, of course, but it's good to be aware of this default behavior when we start positioning objects.
When setting up the new Android project, we target the latest available Android SDK version (4.4.2 at the time of writing this book) and use 2.2 as the minimum SDK version, since this is what GLES2 and the related AnchorCenter branch of AndEngine require. The project we are going to create is just a general, blank Android project without any associated themes or input methods. When presented with the choice to enable any of such options in Eclipse/ADT or another wizard, do not choose any of them. What we need is a blank slate, with only a basic Activity class as the starting point.
During the course of this book, we will use Eclipse/ADT as the development environment. In this IDE, we need to get the AndEngine project imported into the workspace so that in the properties of our new project, we can add it as an Android library dependency. Other development environments will have a similar setup, but we'll leave the details of these as an exercise for you.
When it comes to running Android applications, we get to choose between using a real device (phone or tablet) and an emulator Android Virtual Device (AVD) as the target. Both have their advantages and drawbacks. While Android devices offer the complete experience at full speed, their disadvantages include the following:
AVDs do not have these disadvantages, but they have the following limitations:
Beyond these differences, devices and AVDs are quite similar. Which one to use depends largely on your needs. However, any verification and non-simple debugging should, as a rule of thumb, always be done on a device. While an AVD approaches the functionality of a real device, it is still so different and limited that its results should not be relied upon as real device behavior.
That said, both can be used in an identical fashion with ADB, or the Android Debug Bridge. ADB is a client-server program that consists of a server running on the Android device or AVD, and a client running on the system accessing it. The ADB client can either be run as a command-line tool or be used from within an IDE such as Eclipse for purposes such as uploading applications to the Android device or AVD, uploading and downloading files, and viewing system and application logs in real time.
Especially the ability to view logs in real time for any running application is very helpful to us when we try to debug an application, as we can output any debug messages to the log.
As mentioned before, the easiest way to debug an Android application running on either a device or an AVD instance is to output debug messages to the log output (LogCat) so that they can be read via ADB. The API in Android for this purpose is the Log class. It uses various categories to distinguish between the importance of the messages, ranging from verbose to error.
For example, to output a debug string to LogCat, we use the following code in Java:
The first part is the tag for the application or class that we output from, and the second part is the actual message. The tag is used in filtering to, for example, only see the output from our own application. We can also use a filter on the log category.
When writing native code in C/C++ using theNative Development Kit (NDK), we may also want to use LogCat. Here, we just have to include one header and use a slightly modified function call, like this:
Finally, we can use a debugger. For Java, this is easy, with IDEs such as Eclipse/ADT offering ready-to-use debugging functionality with full integration. This allows easy debugging, adding of breakpoints, and the like. For native code, this is slightly more complex, as we have to resort to using gdb.
The gdb tool is part of the GNU Compiler Collection (GCC), which also contains the compiler used to compile the native code for an Android application. In this case, we want to use its gdb debugger to attach to the native code process on the Android device or AVD so that we can set breakpoints and otherwise monitor the execution.
For gdb to be able to work with such a process, we need to compile the native code with debug symbols enabled, and modify the Android manifest. This involves the following steps:
The NDK contains a script called ndk-gdb that automates the process of setting up gdb, but the essence of what is involved is that we need to push the gdbserver instance onto the device or AVD that we intend to debug on, and connect to this server remotely with gdb. The details of this procedure are beyond the scope of this book, however.
By the end of this book, you will have gained the advanced skills needed to make the most complex AndEngine-based games. These skills will also be useful for other game engines, whether Android-based or not. We will have built a full game application that demonstrates the full possibilities of using AndEngine as the base platform.
These possibilities include advanced graphics options, multiplayer, 3D effects, scene transitions, and user interfaces. With the knowledge gained, you should be able to create your own games with ease, or cooperate with others to make even larger and more complex games.
In this chapter, we went over the basics of Android development, as well as the setting up of a basic AndEngine application. We covered the debugging techniques for both Java-based and native code, and explored the advantages and disadvantages of hardware Android devices and emulated devices. Finally, we looked ahead to what our goals for the coming chapters are, including the development of an application that demonstrates the lessons of these chapters.
In the next chapter, we will build on this basic framework as we extend it to support three-dimensional objects (meshes) in our project.
When using a game engine that limits itself to handling scenes in two dimensions, it seems obvious that you would use two-dimensional images here, better known as sprites. After all, you won't need that third dimension, right? It is when you get into more advanced games and scenes that you notice that with animations, and also with the usage of existing assets, there are many advantages of using a three-dimensional model in a two-dimensional scene.
In this chapter we will cover these topics:
The reasons we want to use 3D models in our 2D scene include the following:
As for the final impact it has on the game's looks, it's no silver bullet but should ease the development somewhat. The quality of the used models and produced animations as well as the way they are integrated into a scene will determine the final look.
The differences between 2D sprites and 3D models can be summarized as follows:
2D sprite
3D model
Defined using a 2D grid of pixels
Defined using vertices in a 3D grid
Only a single observable side
Rotatable to observe any desired side
Resource-efficient
Resource-intensive
A sprite is an image, or—if it's animated—a series of images. Within the boundaries of its resolution (for example 64, x 64 pixels), the individual pixels make up the resulting image. This is a proven low-tech method, and it has been in use since the earliest video games. Even the first 3D games, such as Wolfenstein 3D and Doom, used sprites instead of models, as the former are easy to implement and require very few resources to render.
Because of the available memory and processing capabilities of video consoles and personal computers until the later part of the 1990s, sprites were everywhere. It wasn't until the appearance of dedicated vertex graphics processors for consumer systems from companies such as 3dfx, Nvidia, and ATI that sprites would be largely replaced by vertex (3D) models.
This is not to say that 3D models were totally new by then, of course. The technology had been in commercial use since the 1970s, when it was used for movie CGI and engineering in particular. In essence, both sprites and models are a representation of the same object; it's just that one contains more information than the other. Once rendered on the screen, the resulting image contains roughly the same amount of data. The biggest difference between sprites and models is the total amount of information that they can contain.
For a sprite, there is no side or back. A model, on the other hand, has information about every part of its surface. It can be rotated in front of a camera to obtain a rendering of each of those orientations. A sprite is thus equivalent to a single orientation of a model.
The first question that is likely to come to mind when it is suggested to use 3D models in what is advertised as a 2D engine is whether or not this will make the game engine into a 3D engine. The brief answer here is "No."
The longer answer is that despite the presence of these models, the engine's camera and other features are not aware of this third dimension, and so they will not be able to deal with it. It's not unlike the ray-casting engine employed by titles such as Wolfenstein 3D
