Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learning AndEngine
Learning AndEngine

Learning AndEngine: Design and create Android games with the simple but powerful tool AndEngine

eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Learning AndEngine

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:

Installing the Android SDK

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:

Configuring the Eclipse IDE

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:

Configuring the Eclipse IDE

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:
    Downloading the sources
  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:

Adding AndEngine to the Eclipse IDE

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.

Adding AndEngine to the Eclipse IDE

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:
    Creating a simple Android application
    • 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:
    Creating a simple Android application
  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.
    Creating a simple Android application
  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:
    Creating a simple Android application
  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:

Running the application

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:

Running the application

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:

Adding the required projects

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:

Understanding the 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:

Understanding resolution policies

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).

FixedResolutionPolicy

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.

FillResolutionPolicy

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:

RatioResolutionPolicy

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:

CropResolutionPolicy

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.

Left arrow icon Right arrow icon

Description

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.

Who is this book for?

If you are a beginner to AndEngine, or mobile game development in general, and you are looking for a simple way to start making games for Android, this book is for you. You should already know the basics of Java programming, but no previous game development experience is required.

What you will learn

  • Understand the basics of a game engine
  • Install all the required software and download and set up AndEngine along with its physics extension
  • Design basic game rules and gather game assets
  • Create a basic runnable application using AndEngine
  • Display text and graphics in the game
  • Implement basic interactions between the player and the game, making use of the mobile device sensors
  • Simulate realworld physics ingame
  • Finish a polished 2D physicsbased
Estimated delivery fee Deliver to Slovakia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 11, 2014
Length: 286 pages
Edition : 1st
Language : English
ISBN-13 : 9781783985968
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Slovakia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Sep 11, 2014
Length: 286 pages
Edition : 1st
Language : English
ISBN-13 : 9781783985968
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 112.97
AndEngine for Android Game Development Cookbook
€37.99
Libgdx Cross-platform Game Development Cookbook
€41.99
Learning AndEngine
€32.99
Total 112.97 Stars icon

Table of Contents

12 Chapters
1. Setting Up an AndEngine Project Chevron down icon Chevron up icon
2. Game Concept and Assets Chevron down icon Chevron up icon
3. From Assets to Entities Chevron down icon Chevron up icon
4. HUD and Text Display Chevron down icon Chevron up icon
5. Basic Interactions Chevron down icon Chevron up icon
6. Physics Chevron down icon Chevron up icon
7. Detecting Collisions and Reacting to Events Chevron down icon Chevron up icon
8. Advanced Physics Chevron down icon Chevron up icon
9. Adding a Menu and Splash Scene Chevron down icon Chevron up icon
10. Polishing the Game Chevron down icon Chevron up icon
11. Testing, Publishing, and What's Next 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.8
(6 Ratings)
5 star 83.3%
4 star 16.7%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Marc-Anthony Taylor Nov 05, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Recently I won a copy of Learning AndEngine by Martin Varga and despite having next to no knowledge of Java I decided to give it a go.The book starts with the usual "Setting Up" chapter which is actually quite involved; you really shouldn't skip it. Each step is not only well explained as to how but also to why the steps should be followed. This isn't something I have often come across in beginners guides which are usually only interested in getting you up and running.Throughout the book you work on a single game, this allows you to get to know the individual pieces of the process and, in my opinion, get a better understanding of them. Varga takes care to make sure the steps are manageable and easy to digest.The book takes you from concept to game and doesn't skimp on the details. Each chapter leads nicely into the next letting you build upon what you have learned without taking you out of the process. Assets, physics, testing and publishing are all covered. The book offers everything you need to get you started.Unfortunately, the AndEngine site doesn't seem to be very active (although the forum shows some activity) and the last update to the code was almost a year ago. Nevertheless, although the book focuses on the AndEngine framework I think it would be a good edition to any budding game dev's library.
Amazon Verified review Amazon
Zholaman Kubaliyev Oct 11, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I recommend this books for all who want to develop an Android games using AndEngine. Before to buy I have read some books, articles about AndEngine and it should be noted that this book is the best I found. Thanks to author for good job.
Amazon Verified review Amazon
Mike Jan 05, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Love the way the book has been written. The book is very useful. The Author has explained it very well.The book guides you thoroughly through the early stages of getting everything set up which is one of the most difficult stages to go through, especially with AndEngine.It covers all the major sections of game development, and by the end of the book you have a fully functioning game that you can publish.I would say anyone who wants to learn AndEngine is best off with this book. And once you're comfortable with it, you can go ahead and switch engines if you want because you'll be well grounded in game development theory and practices.
Amazon Verified review Amazon
Bongo Feb 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Wenn man anhand eines einfachen Spieles die Android Programmierung mit der AndEngine lernen möchte ist das Buch sehr zu empfehlen.Es ist übersichtlich und gut verständlich erklärt wie ein Art Doodle Jump Spiel programmiert wird.Man lernt nicht nur das Spiel als solches zu programmieren, sondern auch wie ein Startbildschirm und ein einfaches Menü, Highscore speichern, Sound(und wie er mit einem Button an oder abgestellt wird), Animationen u.a.funktioniert. Ich habe mir das Buch deshalb in englischer Sprache gekauft, weil es leider kein Buch über die AndEngine als deutsche Ausgabe gibt.
Amazon Verified review Amazon
L. Scott May 25, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is really good. Well written and fun to develop the game in deed. I developed my own version and managed to publish it.. http://www.amazon.com/AppDevCoders-Jumping-Goat/dp/B00Y5YTSLEThe author takes object orientation seriously and I love to have a very clean and efficient code.. I can recommend it easily.The engine is good (has everything you may need for sure) but a little slow when you create too many sprites (with physics). It doesn't matter because every year phones (devices) get faster so it won't be a problem.. The only problem is that this game engine is not longer under development (no updates since years).. The Forums are actives and you can find many extensions.
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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela