Home Game Development Learning AndEngine

Learning AndEngine

By Martin Varga
books-svg-icon Book
eBook $25.99 $17.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $25.99 $17.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Setting Up an AndEngine Project
About this book
AndEngine is a very popular open source OpenGL (open graphics library) Android game engine, used to create mobile games quickly while maintaining the ability to fully customize them. This book will guide you through the whole development process of creating a mobile game for the Android platform using one of the most popular and easy-to-use game engines available today. Beginning with the very basics, you will learn how to install AndEngine, gather graphics, add sound and music assets, and design game rules. You will first design an example game and enhance it by adding various features over the course of the book. Each chapter adds more colors, enhances the game, and takes it to the next level. You will also learn how to work with Box2D, a popular 2D physics engine that forms an integral part of some of the most successful mobile games. By the end of the book, you will be able to create a complete, interactive, and fully featured mobile game for Android and publish it to Google Play.
Publication date:
September 2014
Publisher
Packt
Pages
286
ISBN
9781783985968

 

Chapter 1. Setting Up an AndEngine Project

In this chapter, we are going to develop an empty AndEngine application that will serve as a base for a game. First, we will discuss prerequisites and download and install the required software. You will also learn where to get the latest and stable AndEngine libraries from. Lastly, we are going to create and implement a simple Android application that uses AndEngine libraries and then run it.

It doesn't matter on which platform you develop the project as long as you can install the Java Software Development Kit (SDK) and Android SDK there. However, AndEngine is not a multiplatform framework because applications created with AndEngine can run only on an Android device or inside an Android emulator.

 

Prerequisites


Android applications are simply Java applications running inside an Android virtual machine called Dalvik. You will encounter this name when compiling and running the application. The final compiled code is not fully compatible with the Oracle Java Virtual Machine, but for the purpose of this book, you are only expected to know basic Java programming.

You will need the following software and hardware:

  • Windows XP, Vista, 7, or 8; Linux (Ubuntu is recommended); or Mac OS 10.5.8 or a later operating system

  • Java SDK

  • Android SDK with the ADT bundle

  • An Android device

You should already know how to install the Java SDK (JDK) and keep it up to date. The Android SDK requires at least JDK 6. You can use higher versions if available. Always use the latest update for security and compatibility reasons.

Note

It is important to use JDK and not just the Java Runtime Environment (JRE) for development. It is also a requirement of Android SDK. Make sure the JAVA_HOME environment variable is set to the correct folder.

Android SDK contains the Eclipse Integrated Development Environment (IDE) with preinstalled plugins and Android platform tools. Using the latest version of Android SDK is recommended.

Tip

If you have used Eclipse before, you can use your own existing Eclipse installation as well, but then you are required to install the plugins manually on your own.

We are going to download and install Android SDK with the Android Development Tools (ADT) bundle in the next section. ADT allows you to install the application to your device and also connect to it in order to get important information such as the LogCat console output (text output from installed applications that is not visible to users) and other interesting statistics about running apps.

Your device should be running at least Android 2.2, but using a more recent version is recommended. If you don't own an Android device, you can use an Android emulator for development. However, consider getting a physical device because the behavior of the emulator is different from that of a real phone or tablet. The game might run slower or have problems. Emulators are known to have issues especially with hardware-accelerated graphics. Nothing can replace testing on a real device, and in fact for serious game development, it's a necessity to test on multiple devices.

 

Downloading and installing the required software


We are going to download and install Android SDK with the ADT bundle first. JDK 6 or later should already be installed and configured on your development machine.

Downloading the Android SDK

Go to http://developer.android.com/sdk/. If you are on Windows, click on the Download Eclipse ADT with the Android SDK for Windows button. If you are using a different operating system, the page should autodetect it and offer you the link for your OS. In case it doesn't detect it correctly, there is a link called VIEW ALL DOWNLOADS AND SIZES that will expand a list of available platforms. Choose the right platform for you. Be careful when choosing 32-bit or 64-bit software. If you are running a 32-bit Java on a 64-bit system, choose the 32-bit software. Accept the license agreement and save the file to your hard drive. The examples in this chapter are from the 32-bit version for Windows.

Note

There is another IDE available, Android Studio. However, it is in the early access stage. It is not recommended to use this IDE.

Installing the Android SDK

The downloaded file will be a ZIP archive called something like adt-bundle-windows-x86-20131030.zip. The filename indicates the selected platform and the date of release. To install the software, simply unpack the archive to any folder.

Tip

If you have decided to use an existing Eclipse IDE, expand the GET THE SDK FOR AN EXISTING IDE link and click on the Download the stand-alone Android SDK tools for Windows button. Or, download the SDK tools for appropriate platforms from the VIEW ALL DOWNLOADS AND SIZES link. After that, follow the instructions at http://developer.android.com/sdk/installing/.

You should find the following in the folder where you have unpacked the archive:

  • The eclipse folder

  • The sdk folder

  • The SDK Manager.exe file

First, run the SDK Manager.exe file. It might take a while to start, and it doesn't show any splash screen. You will be presented with a window similar to the one in the following screenshot:

Check for any packages that have updates available. Note that you only need the latest SDK, which at the time this book was written was SDK 19 for Android 4.4. The latest version is always bundled with the Android SDK. You should also check the Google USB Driver option.

Note

Every SDK version allows you to write applications that can be deployed to any Android version. If you use a function from an SDK version that is not available in an older Android SDK, the method will not be executed and you will get a warning or an exception. Be careful with that because the code will compile and deploy!

Optionally, you can install the Android emulator system images for older Android versions. This is useful for testing. However, AndEngine can't be deployed to an Android emulator with Android versions 2.x. For now, do not install anything else but the updates and the USB driver. Install the selected packages and close the SDK manager. The installation might take a while, because the packages are downloaded from the Internet.

Configuring the Eclipse IDE

Now, run the Eclipse IDE. From the eclipse folder, run the eclipse.exe file. After the splash, the first thing you will see is the workspace selection window. This is shown in the following screenshot:

If you have never worked with Eclipse, note that a workspace is both a virtual space on your screen (the layout) and a directory where your projects and some metadata that Eclipse keeps about your projects are stored. Choose any directory you want, but make sure it is one with easy access. You can have multiple workspaces. If you check the Use this as the default and do not ask again checkbox, you will be working with this workspace by default and this dialog box won't appear again at the start.

Tip

The workspace selection dialog box is always available by navigating to File | Switch Workspace menu in Eclipse.

After the start, close the Welcome screen and you will be presented with the Eclipse default layout. Parts of the layout can be dragged and dropped to different locations. Also, you can have different perspectives (presets of the opened windows and tabs) for each workspace. We will be using the Java perspective for most of the time but we will also use Dalvik Debug Monitor Server (DDMS) and the Debug perspective for debugging and tuning our application. The perspectives are available by navigating to Window | Open Perspective.

Stay in the Java perspective, but go to Window | Show View | Other… and search for LogCat, as shown in the following screenshot:

LogCat is a log console. The Android system has a logging system that allows developers to print categorized text messages to LogCat from their apps. This is very useful for game developers because the text output to the screen can be very limited. The ADT takes care of getting the LogCat output from the connected Android device.

The Eclipse IDE can be a bit difficult to grasp from the start. However, as a Java developer, you have probably used it before or have used a similar one. Most of the IDEs nowadays are very similar. Try to familiarize yourself with Eclipse before proceeding to the next step.

 

Getting the AndEngine libraries


AndEngine is an open source game engine and the sources are licensed under Apache License Version 2.0. This not only allows us to use AndEngine in both free and commercial games, but it also gives us a chance to inspect or alter the source code. The old way of adding AndEngine to an Android application was to add compiled Java ARchive (JAR) files to your app. This is no longer necessary as you can add AndEngine as a library project.

The author of AndEngine, Nicolas Gramlich, decided to store the whole engine inside GitHub. Git is a version control system (VCS) for source codes and GitHub is a hosting website for Git repositories. A VCS allows you to not only store your sources, but also to store every version of each file. This is of course useful when you need to see the history of your changes or collaborate with more people.

A repository is a logical unit. As a rule of thumb, one repository contains one project. A repository has its address and history separated from other repositories. A repository in GitHub can be forked (creates your own copy with your own history), cloned (creates a version on your machine linked with the repository), or zipped and downloaded locally.

Tip

For more general information about AndEngine, visit the official website at www.andengine.org.

Selecting the correct branch

Android uses OpenGL ES to display accelerated graphics. OpenGL ES is a free API for full-function 2D and 3D graphics on embedded systems. There are several versions of OpenGL ES, namely versions 1.x, 2.x, and recently 3.x.

A repository can also contain multiple branches. Think of a branch as an alternative version of the project. AndEngine is split into three branches. The GLES1 branch uses OpenGL ES 1.0 and it is the oldest. I don't recommend using it. GLES2 is newer and GLES2-AnchorCenter is the newest. They both use OpenGL ES 2. Use the GLES2-AnchorCenter branch if you haven't used AndEngine before. The GLES2-AnchorCenter branch's biggest difference from the GLES2 branch is the fact that point [0, 0] is now in the lower-left corner of the screen. This is the same as in OpenGL and that's why it's recommended.

For the purpose of this book, we are going to exclusively use the GLES2-AnchorCenter branch.

AndEngine repositories

AndEngine is split into a main project simply called AndEngine and many extensions called, for example, AndEngineMultiplayerExtension, which are dependent on the main project. Each project resides in its own repository.

For our game, we need the main AndEngine project and a 2D physics extension called AndEnginePhysicsBox2DExtension. This extension adds a very popular 2D physics simulation framework called Box2D to AndEngine. A lot of popular games use this framework.

There is also a repository called AndEngineExamples. It is not an extension but an application that includes all of the other AndEngine libraries and extensions and illustrates their use.

Tip

If you download all the extensions and the AndEngineExamples project, you can build the AndEngineExamples app and run it on your Android device. An older version is also available online on the Google Play store at https://play.google.com/store/apps/details?id=org.anddev.andengine.examples.

Downloading the sources

You can download the sources from Nicolas Gramlich's original repository at https://github.com/nicolasgramlich/.

However, there is a danger that the codes will be changed any time in the future. For that reason, I recommend to download the sources from my forked repository, which is guaranteed to work with the sources in this book.

The easiest way is to download the complete repository as a ZIP archive, which can be done with the help of the following steps:

  1. Browse to https://github.com/sm4/, switch to the Repositories tab, and select AndEngine. Notice the drop-down menu titled branch. Make sure GLES2-AnchorCenter is selected. Alternatively, you can browse directly to the correct branch by going to https://github.com/sm4/AndEngine/tree/GLES2-AnchorCenter.

  2. The following screenshot is what you should see now:

  3. Click on the Download ZIP button. A file named AndEngine-GLES2-AnchorCenter.zip will be downloaded.

  4. Unpack it in the workspace directory you selected when configuring the Eclipse IDE. Note that the directory is called AndEngine-GLES2-AnchorCenter. It contains the name of the project and the branch name as well. Rename the directory to AndEngine.

  5. Repeat the process for the AndEnginePhysicsBox2DExtension repository. It can be downloaded from https://github.com/sm4/AndEnginePhysicsBox2DExtension/tree/GLES2-AnchorCenter.

  6. Don't forget to rename the directory to AndEnginePhysicsBox2DExtension only. You should have two folders in your workspace directory: AndEngine and AndEnginePhysicsBox2DExtension.

Note

If you decide to use a different branch, remember that extensions used must be from the same branch as the main project.

Adding AndEngine to the Eclipse IDE

In Eclipse, navigate to File | Import and choose Existing Projects into Workspace (under the General folder). Browse to your workspace directory. You should see two projects. Check them both and import them by clicking on the Finish button. This is shown in the following screenshot:

If you have installed the ADT bundle with Android SDK 19, you should see no errors. In case there are errors, try cleaning and building all projects again. Simply click on the Project drop-down menu in Eclipse's main menu and select the Clean… option while having the Build Automatically option checked.

It is possible that when you were installing the ADT bundle, it contained a different SDK version from 19, or maybe you are, for some other reason, using a different version. In that case, you will see messages like the following in the console:

[2014-01-14 15:36:11 - AndEngine] Unable to resolve target 'android-19'

Right-click on the project, select the Properties option, and then choose the Android option. Make sure that the Android SDK version of your choice (or simply the latest) is selected. This is shown in the following screenshot. You will probably have to clean the project to make the error disappear. We have to do this because the project was saved with SDK 19 selected. Do it for both projects.

 

Creating a new application


We will first create an empty Android application project and later add the AndEngine libraries.

Creating a simple Android application

To create a simple Android application, we will follow these steps:

  1. Go to File | New | Android Application Project in Eclipse. You will be presented with the window shown in the following screenshot:

    • Application Name: This is visible under the app's icon on your phone. When creating a real application/game, give it a meaningful name. Let's say your game is called Awesome Football Manager. You can simply put this in the Application Name field, but on the phone, you will probably see only Awesome Foo... under the icon, due to the limit of characters that can be displayed.

    • Project Name: This is just the project name in Eclipse, and it is how your APK (Android Application Package—the final archive to be deployed to the device) will be named. I recommend using a single word derived from your application name.

    • Package Name: This is used for your Java code and it is also a unique identifier for the Google Play store. Make sure your chosen package name is not taken! If you have your own domain, put it there (backwards). If you don't have one, imagine that you do and what it would look like. My domain is kul.is; therefore, my package starts with is.kul and the full package name will be is.kul.learningandengine.

    • Minimum Required SDK: This is simply the lowest Android version that you are going to support. AndEngine works well with SDK 8, but if you are going to use big textures, you might run into problems. It is always a trade-off between supporting as many devices as possible and making sure that the application will work on all supported devices. The lower the SDK, the more problems you can expect and the more devices you should test. On the other hand, more devices will be supported and you will reach a broader user base. Android 2.2 and 2.3 are still used today.

    • Target SDK and Compile With: For these, pick the highest available SDK (19). You should own a device with the target SDK, or test the application in the emulator.

    • Theme: For this, select None. Your activity theme won't be visible, so don't bother with it. Our game in AndEngine will use an overlay view that will cover the whole available screen.

  2. Click on the Next button to continue the application creation wizard.

  3. On the next page, uncheck the Create custom launcher icon option. This option will launch another wizard where you can upload an image that would serve as your app icon in the store and on the device. We will keep the default green Android icon for now.

  4. Keep the Create activity option checked. An activity is a single, focused thing that the user can do (in our case, play the game, but it can be for example, check emails or record voice), and it represents the presentation layer of an Android application. It is also a Java class that extends the Activity class from the Android library. Have a look at the following screenshot:

  5. Click on the Next button to advance to the Create activity page as shown in the following screenshot. Leave everything as it is and click on the Next button again. We are creating a blank activity, but in fact, it doesn't matter. We are going to change the activity anyway. We are using this option in order to get the Activity class created for us in the right package.

  6. The last page allows us to name the activity and the layout. We are not going to work with the layout in this book, so you can leave it as it is. We are going to name the activity GameActivity. This is shown in the following screenshot:

  7. Click on the Finish button to close the wizard. A new project will appear in the Eclipse Project Explorer window (the tab on the left). You can run the project now, but your device must be configured properly. First, plug in your Android device.

Device configuration

You need to enable the USB debugging option under Developer options on your phone or tablet in order to deploy the application from Eclipse. The configuration differs across Android versions, and it can even differ for the same version on a different device or brand.

Before Honeycomb

Honeycomb is the codename for Android 3.0. In versions prior to Honeycomb, the developer options are located under Settings | Applications | Development.

Honeycomb until Ice Cream Sandwich

You will find the Developer options button under Settings | Developer options in the System subsection.

Jelly Bean and later

The developer options are hidden starting with Android 4.2. You need to use the following trick to activate the option:

  1. Go to Settings | About phone.

  2. Scroll down to the Build number option.

  3. Tap on this option seven times. On the third tap, you should see the message about four taps remaining to become a developer.

  4. Go back to the Settings window.

  5. You should see the Developer options menu item in your Settings window.

Check the USB debugging option. This should be all that is required to upload the application from Eclipse to your device.

Tip

Consider turning on the Unknown sources option under the Security option as well. Basically, it means you can install APKs from other sources than the Google Play store. This is useful for testing when you upload a production APK directly from your development machine to the device. The development versions of apps are allowed thanks to the USB debugging option.

Running the application

Connect the device using a USB cable. You should see a notification of USB debugging connected on your phone or tablet.

Finally, in Eclipse, select the project and click on the drop-down arrow next to the run icon in the Eclipse top bar. Navigate to Run As | Android Application. This is shown in the following screenshot:

A pop-up window named Android Device Chooser will show the list of connected devices. Select your device. You can also check the Use same device for future launches option, which will remember your device for this session and will use it as the default target when you run the application the next time. Your device must run the project's minimum Android SDK or higher.

Note

If you don't have a physical Android device, the Android Device Chooser window will allow you to define a virtual device using the Android emulator.

Have a look at the following screenshot:

After clicking on the OK button, Eclipse will build the application and create an APK. All applications have to be signed using a certificate before publishing to the Google Play store. For development purposes, all APKs are signed using a debug certificate.

The APK is then uploaded to the device and the main activity, in our case GameActivity, is started. You should see a simple one-screen application with Hello World text on the display. This is a default Hello World Android application created by Eclipse.

Adding AndEngine

We need to add the AndEngine and AndEnginePhysicsBox2DExtension libraries to our app and change the GameActivity.

Adding the required projects

AndEngine and all the extensions are library projects. That means they can be added to our application as dependencies, similar to adding an external library JAR file. Eclipse will then build and package the library project along with our application to the final APK.

Right-click on the project, select Properties, and choose Android. Click on the Add button in the Library subsection and select AndEngine. Also add the AndEnginePhysicsBox2DExtension project similarly. This is shown in the following screenshot:

Changing the GameActivity to an AndEngine activity

AndEngine extends the basic Android Activity class because it needs to take care of a lot of initializing and loading of resources for the game engine. AndEngine gives us several hooks that we can use to perform our own initializations.

Understanding the activity lifecycle

It is important to understand the lifecycle of an Android application and activities. For a basic game, a single activity is usually enough, making things simpler. The following diagram describes the most basic activity lifecycle:

When you start your application, it goes through different states and the callback methods onCreate, onStart, and onResume are called. Notice that the onResume method is called even on the first start.

An activity is paused typically when the screen is locked or a dialog activity is brought to the front. Imagine a low battery warning for example. An activity is stopped when another activity completely covers your activity. This can be an incoming call. Note that the onStop method doesn't have to be called. This can happen when the system doesn't have enough resources for another activity and decides to kill your activity right away. The final method, onDestroy, is called when your activity is finished and cleared from the memory. Again, it is not guaranteed to be called.

The lifecycle is more complex than this and there are even more hooks that can be overridden and used. For our purposes, this will be enough. In fact, AndEngine takes care of most of the methods and gives us a few convenient methods to use instead.

The BaseGameActivity class

Our GameActivity class extends the BaseGameActivity class, which implements basic game activity behavior for us. For example, it implements the onCreate method that configures the engine and the surface view. The surface view is a dedicated drawing surface for our game that we can use through AndEngine.

When you created the empty GameActivity, it looked like the following code (it can differ based on the Eclipse and ADT versions):

package is.kul.learningandengine;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class GameActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.game, menu);
    return true;
  }

}

Delete both the onCreate and onCreateOptionsMenu methods. Change the parent of the GameActivity class from android.app.Activity to org.andengine.ui.activity.BaseGameActivity.

BaseGameActivity is an abstract class, and it will make you implement the onCreateEngineOptions, onCreateResources, onCreateScene, and onPopulateScene methods. The lifecycle methods are all handled by AndEngine.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. 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.

The onCreateEngineOptions method
  1. First, define the onCreateEngineOptions method. This method is called from the onCreate method and it is run first. You are supposed to configure AndEngine's engine in this method. The following is a typical example:

    public static final int CAMERA_WIDTH = 480;
    public static final int CAMERA_HEIGHT = 800;
    
    @Override
    public EngineOptions onCreateEngineOptions() {
      Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
      IResolutionPolicy resolutionPolicy = new FillResolutionPolicy();
      EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, resolutionPolicy, camera);
      engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true);
      engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
      Debug.i("Engine configured");
      return engineOptions;
    }

    We have defined two static constants that define the resolution of our view port. AndEngine will then take care of scaling the final picture on the device.

  2. In the method itself, we start with the camera definition. The Camera object defines the part of the scene that will be visible. It takes four parameters: the first two are the bottom-left coordinates in the scene and the third and fourth are the width and height of the visible area.

  3. Next, we define a resolution policy. The Android platform suffers from a variety of different screen sizes and ratios. AndEngine tries to deal with this by letting you specify one resolution and then scaling the resulting picture to any device.

  4. You don't need to care whether the screen size of the phone is bigger or smaller than your desired resolution. AndEngine can enlarge your scene or shrink the picture. You place your objects at coordinates in your resolution. However, you still have to hint AndEngine about how the resulting picture should be scaled, and that's what the resolution policy is for.

  5. In the example, we are using the FillResolutionPolicy. As the name suggests, this policy fills the whole screen with your scene. Your picture will be resized but the aspect ratio will not be kept, unless the phone and your scene have the same ratio. Pixels can become taller or wider.

  6. Then, we create the EngineOptions object. This is the final object that will be passed to the engine. It takes four parameters, as follows:

    • Fullscreen: This option is set to true, as we want our game to cover the whole screen.

    • Screen orientation: For this, the possible values are PORTRAIT_SENSOR, PORTRAIT_FIXED, LANDSCAPE_SENSOR, and LANDSCAPE_FIXED. The sensor variant will flip the picture upside down when you flip the device.

    • Resolution policy: This is explained earlier.

    • Camera: This is explained earlier.

  7. We also set the audio options simply to indicate that we will be using both sound and music.

  8. Last, we set the wake lock to SCREEN_ON. This simply means that the device will not enter sleep mode due to inactivity. This is important because you can have a period in your game without user input when you don't want the screen to turn off by itself. This can be a cutscene for example.

  9. The line Debug.i("Engine configured"); is optional. This will print the Engine configured message to LogCat. Use this kind of debug message to check whether the method ran successfully.

    Tip

    The messages can have different levels: error, warning, info, debug, and verbose. Each level has its own method, such as Debug.e or Debug.d. These are used to differentiate the severity of the method as LogCat allows filtering by the level. You can use Debug.i("MyTag", "Engine configured"); in your code to further categorize your messages based on tags.

  10. At the end, we return the engineOptions object.

The onCreateResources method

The onCreateResources method is called after the engine options are created, and it is used to initialize game resources such as graphics, sounds, and music. For now, we leave this method empty.

@Override
public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback)throws IOException {
  pOnCreateResourcesCallback.onCreateResourcesFinished();
}

Notice the pOnCreateResourcesCallback parameter. This is used to indicate that you are done loading the resources and the control is given back to the engine. You have to call the onCreateResourcesFinished method, otherwise the engine will not continue.

The onCreateScene method

The onCreateScene method is called from the onCreateResourcesCallback object when you call the Finished method. It is used to create a scene object or objects.

Note

Every displayable object in AndEngine is an entity. That includes the scene, which is the parent of all the other entities currently displayed. The engine can display one scene at a time, and you will typically want to define multiple scenes, such as a menu scene and a game scene. You can also have child scenes, which are used to display a pause screen or a game over screen.

The following code describes the simplest scene. We only create an empty scene object and set its background to cyan color.

@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)throws IOException {
  Scene scene = new Scene();
  scene.getBackground().setColor(Color.CYAN);
  pOnCreateSceneCallback.onCreateSceneFinished(scene);
}

Again, you have to call the Finished method on the provided callback object to tell the engine you are done creating your scene.

The onPopulateScene method

The onPopulateScene method is the final method we need to implement, which is used to populate the scene with entities. For the simplest example, we are not going to add any. Leave the method body empty, but remember to return the Scene object. This method is called from the Scene callback and you have to call the next callback too. This is described in the following code:

@Override
public void onPopulateScene(Scene pScene,OnPopulateSceneCallback pOnPopulateSceneCallback)throws IOException {
  pOnPopulateSceneCallback.onPopulateSceneFinished();
}

Tip

There is an alternative to BaseGameActivity called SimpleBaseGameActivity which calls the callbacks for you at the end of each of the onCreateResources, onCreateScene, and onPopulateScene methods. It's up to you which one you want to use, but you should understand what the callbacks are doing.

Running the application

Run the application and you should see an empty screen with a cyan background. You can refer to the full source code for this chapter in the code bundle.

 

Understanding resolution policies


In the previous section, we configured the engine with FillResolutionPolicy. Dealing with different screen resolutions can be a big issue, and it is one of the most difficult topics to grasp for beginners. Especially for the first game, you should choose a single resolution and prepare all your graphics assets as if you were showing them in this resolution only. Let the engine deal with scaling and shrinking.

As you have learned before, AndEngine deals with different screen resolutions and rations by using resolution policies. There are several of them, and they are suitable for different scenarios.

Let's say you want to work with a resolution of 800 x 480 px. Your square is 80 x 80 px large. Let's add three of them to the scene. So, this is how you want your scene to look. The bottom-left square is placed at [50, 50]. AndEngine calculates where to display it in different resolutions.

It should look like the following screenshot:

Let's see what this would look like on a Google Nexus 4 using different resolution policies. The Google Nexus 4 has a resolution of 1280 x 768 px.

FixedResolutionPolicy

This policy simply creates a renderable area of specified size. If your screen is 1280 x 768 px like on the Nexus shown in the following screenshot, the 800 x 480 px scene will be centered with a big border. If your screen size is exactly 800 x 480 px, your scene will perfectly fit on your display. If your device has a smaller resolution, the whole scene will be cropped. This policy keeps the aspect ratio of pixels (squares will be squares).

You can of course pass anything to your FixedResolutionPolicy. It doesn't have to be the same as the camera dimensions. You can measure the display size of the device and then manually position all elements based on this measurement. That's what this policy is for.

FillResolutionPolicy

As mentioned earlier, the FillResolutionPolicy fills the screen but can distort the image because it doesn't keep the scene ratio.

You can see in the previous screenshot that on the Nexus 4, the difference is almost unnoticeable, because 800 x 480 px ratio is about 1.66, and the Nexus 4 screen ratio of 1280 x 768 is 1.66 too. But thanks to the soft buttons in the system bar, the usable portion has roughly 1.56 screen ratio, and that's why the squares are slightly taller.

RelativeResolutionPolicy

You have to pass two floats to this policy, which are the percentages of width and height of the screen you want to use. So, if you pass (1, 1), it means give me the whole screen (the same as FillResolutionPolicy).

RatioResolutionPolicy

A ratio policy is probably the most commonly used in the examples. It keeps the aspect ratio and scales your scene to fit one dimension. The other dimension will be padded with the background color of your theme. It will create two bars.

They are highlighted with yellow in the following screenshot:

If you set your background theme to be black, the bars will be black. If you use this policy, try to match the theme background color to your game's background.

CropResolutionPolicy

This policy was originally created by user jgibbs on the AndEngine forums. He called it CroppedResolutionPolicy. You will find a slightly modified version of it in my GitHub repository.

The crop policy is similar to the ratio policy, but instead of padding, it scales the scene while keeping the aspect ratio to cover the whole screen and crops the overflow. See the arrows in the following screenshot pointing to the areas that will be cropped:

This policy is not the easiest to use. You must place the objects relative to the edges. The center of the screen will still be the center, but you can't simply say: place sprite at [0, 0]. It might be in the overflow on some devices.

 

Summary


In this chapter, we learned how to set up our environment in order to develop AndEngine games. We saw how to create a new Android application and how to implement a foundation for an AndEngine game. Basic AndEngine parameters were explained. We also covered one of the most difficult and important topics—the resolution policies.

In the next chapter, we will draft our game idea and prepare the graphics, sound, and music assets.

About the Author
  • Martin Varga

    Martin Varga is a professional Java developer with a passion for teaching and developing mobile games. He has worked as a senior software engineer in several domains, including telecommunications, mentoring juniors and leading teams of developers. When it was announced that Java will be the language of choice for the Android mobile platform, he seized the opportunity and started his indie game developer career. He is the author of Mr. Dandelion's Adventures, an Android game made with AndEngine, and a few other games used in his tutorials, which are published on his website http://android.kul.is. Alongside the tutorials, he is also trying to promote other indie developers' games and writing game reviews. He's an active member of the AndEngine community and several game development websites, answering questions of newcomers in the indie game development scene daily.

    Browse publications by this author
Learning AndEngine
Unlock this book and the full library FREE for 7 days
Start now