Greetings!

The main purpose of this website is to support Android indie game developers with tutorials, reviews and promotion of their games. The main difficulty for the developers is not to make the game, but to get exposure. To get it out there. If you find anything useful here, please spread the word. Like my page on Facebook, follow me on Google+ or Twitter. Thank you!

Google+ Facebook Twitter

× close

Sunday, 25 August 2013

AndEngine Tutorial - Getting Started

This tutorial is part of AndEngine basics.


<< List of all tutorials

There are few good tutorials about how to get started with AndEngine. But they are video tutorials and if you are like me and can't follow videos, here's a tutorial for you. If you like it, there's a good chance you will this book about AndEngine as well.

AndEngine is a 2D OpenGL ES game engine for Android, developed by Nicolas Gramlich. OpenGL is usually used for 3D graphics, but with certain settings (orthographic projection) it can work very well for 2D.

AndEngine is a game engine. It's not a game creation system. Most of the apps for Android are written in Java. It's the same with AndEngine - it's just a library that helps you take care of some aspects of your game. This tutorial requires you to already know Java, know how to install Java on your computer and basic Java programming. It also expect you to have an Android device; phone or tablet. In later tutorial I will cover installing a suitable emulator, but you can't replace testing on a real device. I use Windows, so everything I say applies to Windows. It should be pretty straightforward to apply it to other OS too.

Let's get started. If you find something unclear or hard to understand, please comment on the article below. Note: You can see the original size of any image by clicking on it.

Install and prepare required software

Install latest Java JDK. Grab the one that says just JDK, you won't need NetBeans IDE. The IDE of choice for Android is Google's version of Eclipse. There is another IDE coming, Android Studio, but it is in early access stage. So just forget it for now.

Install Android SDK with adt bundle. Download it from the linked page - agree to the EULA and choose the right version for you (32-bit or 64-bit). If you are running 32-bit Java on 64-bit system, choose 32-bit. You can also download just the adt bundle and use your existing Eclipse. This is not covered here.

The downloaded file should be something like: adt-bundle-windows-x86-20130729.zip. Simply unpack it to a directory of your choice. First run the file "SDK Manager.exe". It might take a while to start and it doesn't show any splash screen. Give it time. You will be presented with this screen:



Check any packages that have update available. Note that you only need the latest SDK, which now is SDK 18 - Android 4.3. Every SDK version allows you to write applications that can be deployed to any Android version. If you use a function from SDK 18 that is not available for older Android phones, the method will not be executed and you will get a warning or exception. Be careful with that. But the code will compile and deploy!

After the update, close it. You can of course install any packages you think you need. But for this tutorial, the default are enough. The SDK Manager is accessible from Eclipse too.

Now run eclipse: adt-bundle-windows-x86-20130729/eclipse/eclipse.exe. After the splash, the first thing you will see is this:



If you have never worked with Eclipse, note that 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 one with easy access. You can have multiple workspaces. If you check the "default" checkbox, you will be working with this workspace by default and this dialog won't appear again at the start. It is always available from the File menu in Eclipse.

After the start, close the Welcome screen and you will be presented with Eclipse default layout. Everybody prefers something else but you will see my layout later on the screenshots. Everything can be drag-n-dropped, play around. Also you can have different perspectives for each workspace. I will explain this later in a tutorial about debugging.

Download and unpack AndEngine sources

AndEngine is Open Source, licensed under Apache licese v2. You can use if for your commercial games and you can license your games as you wish. You can also make modifications to the engine, but then you have to make the modifications available for public.

The official location of AndEngine sources is GitHub. You will only need the basic AndEngine library for this tutorial.
 

There are more extensions available plus a project with examples and you will actually need all of the extensions to be able to compile and run the AndEngine examples, but let's not complicate things for now. I will cover the extensions and examples in the next tutorial.
Notice that there are several branches of AndEngine. The GLES1 branch deals with OpeGL ES 1.0 and it is the oldest. I don't recommend using it. GLES2 is newer and GLES2-AnchorCenter is the newest. Use the GLES2-AnchorCenter if you haven't used AndEngine before. AnchorCenter branch biggest difference from the GLES2 vanilla is the fact that point 0,0 is now in lower left corner of the screen. This is the same as in OpenGL, that's why it's recommended.

GitHub is a versioning source code repository (like SVN or CVS) but to make things simpler, click on Donwload Zip button. Versioning systems are widely used in software development, sooner or later you might want to go back and use it. For your own benefit. Check my other tutorial on GitHub to see the alternative way to download the sources.

Unpack the file AndEngine-GLES2-AnchorCenter.zip to your workspace directory. Rename the "v" directory to "AndEngine". Then In Eclipse, select File -> Import and choose Existing Projects into Workspace. Browse to your workspace directory. This is what you should see. Import the project by clicking on Finish.




 If you have installed the adb bundle with SDK 18, you will see the following message in your console:

[2013-08-25 15:36:11 - AndEngine-GLES2-AnchorCenter] Unable to resolve target 'android-17'
[2013-08-25 15:36:11 - AndEngine-GLES2-AnchorCenter] Project compiler settings changed. Clean your project.

Actually you will be seeing this quite often. Let's deal with it: Right click on the AndEngine project, select Properties and choose Android. There should be just one option to select. Do it and click OK. You will probably have to Project -> Clean the project to make the error dissapear (that's just lazy Eclipse). We had to do this, because the project was saved with SDK 17 selected. Now we don't have it, so we have to select the one we have.


Hello World

What kind of tutorial doesn't give you a Hello World, right? Go to File -> New -> Android Application Project


Application name is going to be visible under the app's icon in your phone. When creating a real application/game, give it some meaningful name. Project name is just the project in eclipse - this is how you apk will be named. I recommend using a single word derived from your Application name. Let's say your game is called Awesome Football Manager. This you can simply put in Applicaiton Name, but on the phone you will probably see "Awesome Foo..." under the icon, due to limit on number of displayable letters. 

Package name is used for your java codes. 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. Note that the package is the unique identifier used in Google Play store and all the other alternative stores. Make sure your chosen package name is not taken! My domain is kul.is, therefore my package starts with is.kul.

Minimum target SDK 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. I will cover this in later tutorials.

For Target SDK and Compile with pick the highest available SDK (18) and do this always. It makes no sense to pick anything else unless you need to reproduce some old bug.

For Theme select none. You activity background won't be visible, so don't bother with it. You might see some ugly bars around your picture. This is out of scope of this tutorial for now.

Click Next. Deselect "Create custom launcher icon", we are not going to waste our time now for eye candy. Click Next again and you will see Activity creator Wizard. "Blank activity" should be selected". Select it if it is not and Next.

The next screen allows you to customize your activity. The only important thing for now is the activity name, which will be the same as the Class name of the activity. Just keep everything default and press Finish.

Now you have created an empty Android application (not AndEgine yet). Plug in your Android device and try it out. Make sure you have enabled USB debugging on your Android device. If not, tap Settings, scroll down to { } Developer options and enable it. Click the green play button in the Eclipse top panel and select Run As -> Android application.


Next popup will appear. It should list your Android device. Here you can see my chinese tablet identifying itself as "unknown-q88". I highly recommend doing this with real device and not the emulator. But I will get to emulators later. Clicking on Use same device... is recommended until you get to stage when you test with multiple devices.



You app should start on your device. If not, you will have to troubleshoot it - it's not related to AndEngine yet.

Another popup should appear asking you if you want to auto monitor messages from your app using LogCat. Select yes. I will conver LogCat and Debugging in separate tutorial. But fo now, select yes and check the LogCat tab that was added to Eclipse. It contains usefull messages from your app and all the other apps. This is something you will want to use later.

If you did everything right, you should see Hello World message.

Adding AndEngine to Hello World

Right click on your project and select Properties. Choose Android. Click add and select the only available option there. This is how it should look like after you add it. Click OK.





That was a lot of configuration, downloading, let's see some code! Open MainActivity.java. Tip: You can use Ctrl+Shift+R to quickly open any resource in your workspace. Press it and type Main... you will see MainActivity as one of the options.

This is how it should look like:


package is.kul.tutorial.helloworld;

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

public class MainActivity extends Activity {

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

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

}

Disclaimer: Android authors chose Hungarian notation for Android code style. There's a great debate on the internet whether this notation is good or bad. Without starting any flames, Nicolas used the same notation for his engine. I will try to follow it too in the tutorials. You will see it more often than not, get used to it. It will make your life easier. See details on this page.

Download the following image, name it "helloworld.png" and place it in your workspace in the Tutorial_1_HelloWorld/assets folder:



Now replace the code in MainActivity with this code:

package is.kul.tutorial.helloworld;

import java.io.IOException;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.util.FPSLogger;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.bitmap.AssetBitmapTexture;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.adt.color.Color;


public class MainActivity extends SimpleBaseGameActivity {

  private static final int CAMERA_WIDTH = 800;
  private static final int CAMERA_HEIGHT = 480;

  private ITexture mHelloWorldTexture;
  private ITextureRegion mHelloWorldTextureRegion;


  @Override
  public EngineOptions onCreateEngineOptions() {
    final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);

    return new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR, 
        new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
  }

  @Override
  public void onCreateResources() throws IOException {
    this.mHelloWorldTexture = new AssetBitmapTexture(this.getTextureManager(), 
        this.getAssets(), "helloworld.png");
    this.mHelloWorldTextureRegion = TextureRegionFactory.extractFromTexture(
        this.mHelloWorldTexture);
    this.mHelloWorldTexture.load();
  }

  @Override
  public Scene onCreateScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());

    final Scene scene = new Scene();
    scene.getBackground().setColor(Color.YELLOW);

    final float centerX = CAMERA_WIDTH / 2;
    final float centerY = CAMERA_HEIGHT / 2;

    final Sprite sprite = new Sprite(centerX, centerY, 
        this.mHelloWorldTextureRegion, this.getVertexBufferObjectManager());
    scene.attachChild(sprite);

    return scene;
  }

}

You can see almost the same example in AndEngineExamples project, in SpriteExample.java. But when you try to import the Examples project now, it will most likely fail. Let's deal with examples in the next part.

When you run this application, you should see this:



For now, let's just go through this code and explain bit by bit what each part means.


public class MainActivity extends SimpleBaseGameActivity {

SimpleBaseGameActivity extends BaseGameActivity. Every Activity in AndEngine should have BaseGameActivity as one of it's ancestors. SimpleBaseGameActivity then implements some functionality (callback after some events) that you not always need to customize. In real game you will probably want to extend only BaseGameActivity and implement the callbacks yourself.

  @Override
  public EngineOptions onCreateEngineOptions() {
    final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);

    return new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR, 
        new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
  } 

This method tells the engine, how it should behave. You create camera here, because you then pass it to the engine. For now you want the camera to view the whole scene, so set it to the same size as the resolution.

Notice the EngineOptions.
  • First parameter is whether you want to run in fullscreen.
  • ScreenOrientation simply tells the app how to behave, when you rotate the device. There are four options, fixed and sensor for both landscape and portrait. Sensor means the engine will rotate the screen when you turn the device upside down.
  • resolution policy is one of the trickiest thing ever. Let's just say that the two bars you might see around your screen are caused by that. The rule of thumb is that you specify resolution (and resolution policy) that best suits your game and the engine will take care of all scaling. 
    • Let's say we set the camera width x height as 800x480 but your phone has resolution 1280x720 - no problem, with ratio resolution policy, the engine will scale your scene from 800x480 to 1200 x 720 and leave the two 40px wide bars on the left and right. And you will be still placing entities in the scene as if it was 800 pixels wide and 480 pixels high.
    • It's really not complicated, but choosing the right policy is difficult.
  • And the camera

  @Override
  public void onCreateResources() throws IOException {
    this.mHelloWorldTexture = new AssetBitmapTexture(this.getTextureManager(), 
        this.getAssets(), "helloworld.png");
    this.mHelloWorldTextureRegion = TextureRegionFactory.extractFromTexture(
        this.mHelloWorldTexture);
    this.mHelloWorldTexture.load();
  }

Create all resources here. We only have one image. You need to understand three basic terms here:
  • Texture - this is a bitmap representation of an image in your device's memory
  • Texture Region - is a part of texture
  • Sprite - is a virtual entity that is linked with the Texture Region and displays it.
So we create a texure object, define a region and then load the texture from the file to memory. 

  @Override
  public Scene onCreateScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());

    final Scene scene = new Scene();
    scene.getBackground().setColor(Color.YELLOW);

    final float centerX = CAMERA_WIDTH / 2;
    final float centerY = CAMERA_HEIGHT / 2;

    final Sprite sprite = new Sprite(centerX, centerY, 
        this.mHelloWorldTextureRegion, this.getVertexBufferObjectManager());
    scene.attachChild(sprite);

    return scene;
  }

Last method creates the Scene. It's a good idea to register the special handler for displaying framerate. You will see it printing FPS messages to LogCat.

Here I simply create a yellow background and put the Sprite in the middle of the picture. See how you create a sprite. You have to pass it position, texture region to display and then vertex buffer object manager (vbom). The vbom is out of the scope of this tutorial, for now we can say, just do this always...

Summary

This is it. You should have a working HelloWorld example running on your phone. Start by exploring the Examples. I promise I will post a tutorial how to open all the other projects and fix problems soon. You can tr it yourself. Simply download all extensions from Nicolas' GitHub, add them to Eclipse, fix the projects setup.

Next: AndEngine Extensions and AndEngine Examples

Further reading

You can see the list of books about Android Game Development for further reading, not just about AndEngine but game development in general.

If you have any questions, you can contact me on Google+, post on the website's Google+ page, Facebook page or simply send me and email to android@kul.is.
Martin Varga is a Czech software developer who likes pygmy owls (hence Kulíš), running, ramen, travelling and living in foreign countries. He is also known as smartus or sm4 on the internet (read as smartass, but there are too many of them). He currently tries to make games in AndEngine like Mr. Dandelion's Adventures and hangs around a lot at the AndEngine forums.