Skip to content

Getting Started: The Work Order of AndEngine

September 10, 2011

Elements of BaseGameActivity

Before getting started with your AndEngine project, let’s take a look at the flow of BaseGameActivity.  It’s very likely that at least a large portion of your app will extend BaseGameActivity, so it’s important to understand how the pieces of it fit together.

Each BaseGameActivity must contain 4 major elements: onLoadComplete, onLoadEngine, onLoadResources, and onLoadScene.  We’ll look at these in the order of which they are called, and then we’ll look at a few additional elements that may be useful.

OnLoadEngine

First, OnLoadEngine is called.  This command is where you define your engine.  Usually, it will look something like this:

	@Override
	public Engine onLoadEngine() {

		//sets up the engine
		this.camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		final EngineOptions engineOptions = new EngineOptions(true,
				ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(
						CAMERA_WIDTH, CAMERA_HEIGHT), this.camera);

			engineOptions.setNeedsSound(true);
			engineOptions.setNeedsMusic(true);

		return new Engine(engineOptions);

	}

This example sets up an engine with a Camera (utilizing 2 values that must be defined in the file) and some options (which are, in this instance, whether or not the game is fullscreen, the screen’s orientation, the resolution, and the camera used by the scene).  Before I return the engine, I make sure the game knows that it will be using both sound effects and music.  What this code does is essentially create a blank canvas on which the rest of the game’s code is written.

OnLoadResources

Next, OnLoadResources is called.  In this section, you pre-load all the resources your game will be using regularly.  This can be beneficial because, as you know, games often reuse sprites and textures.  For example, if you have a character that shoots a laser at a rate of 2 times per second, it would be far more inefficient to create each laser as it is made.  In addition, if you were to load all your resources into memory after the game had begun, you would experience major slowdown whenever a new resource is loaded- and that’s bad.  In some instances, it could even cause instability, or cause things to function incorrectly- my game requires multiple music files to be playing at the same time, and even a tenth of a second of desynchronization would sound terrible.  Therefore, it’s just a good idea to get that out of the way here- load as many resources as you foresee using.  Here’s a sample:

@Override

	public void onLoadResources() {

	LaserFrequency = 4;
	CurrentScore = 0;
	HitPoints = 10;

	this.mBuildableTexture = new BuildableTexture(512, 512, TextureOptions.DEFAULT);
	TextureRegionFactory.setAssetBasePath("img/");
	mLaserTextureRegion = TextureRegionFactory.createFromAsset(this.mBuildableTexture, this, "laser.png");
	GameActivity.mShipTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mBuildableTexture, this, "maincharacter.png", 4, 1);
	GameActivity.mEnemyTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mBuildableTexture, this, "enemy.png", 4, 1);

	FontFactory.setAssetBasePath("font/");
	font_texture = new Texture(256, 256, TextureOptions.BILINEAR);
	font = FontFactory.createFromAsset(font_texture, this,"pf_tempesta_five.ttf", 60, true, Color.BLACK);

	this.mEngine.getTextureManager().loadTextures(mBuildableTexture, font_texture, font_texture);
	this.mEngine.getFontManager().loadFont(font);

	SoundFactory.setAssetBasePath("snd/");
	GameActivity.explosionSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(),this, "explosion.ogg");
	GameActivity.gameOverSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "gameover.ogg");
}

Okay, so in this example, I’m doing 4 things.

(1)- I’m setting up a few variables.  It’s always a good idea to set all your variables in the onLoadResources section, so that you don’t end up with any leftover values causing you trouble.  For example, on my first game, I forgot to set the score variable to 0 in onLoadResources, and so every new game, the score was just added to the previous one.  Resetting it in onLoadResources fixed it immediately!

(2)- I load a few textures.  I load a character texture, an enemy texture, and a bullet texture here.  You may notice the character looks different than the bullet- that’s because the character is animated.  We’ll discuss this further later.

(3)- I load a font for use in in-game text, such as score displays or progress updates.  Chances are, you won’t want to use the built-in fonts for everything.  Fortunately, AndEngine has a great font manager- more on that to come.

(4)- lastly, I load a few sound files.

If any of this doesn’t make sense to you, don’t worry- we’ll be getting there soon.  In the meantime, just understand that this is the place where you load all the resources that you will put into your app.

OnLoadScene

Third, OnLoadScene is called.  This is where all your behavior is defined.

	@Override
	public Scene onLoadScene() {
		this.mEngine.registerUpdateHandler(new FPSLogger());
		level.getScene().setBackground(ParallaxBackground);
		level.getScene().getTopLayer().addEntity(healthbar);
		level.getScene().registerUpdateHandler(new TimerHandler(((20-CurrentLevel)/5), new ITimerCallback() {
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				pTimerHandler.reset();
				enemy.release;
					}
				}
			}
		}));

		level.getScene().registerUpdateHandler(new IUpdateHandler() {
			@Override
			public void onUpdate(float pSecondsElapsed) {
				checkCollisions();
			}
		});
		ship.addToScene(level.getScene());
		//fires the laser and spawns some of the enemies based on upgrades
		return level.getScene();
	}

So, in this example, we started by setting up the FPS logger, then added the background, a health bar, two update handlers (one to make enemies attack at a regular interval, and one to check for collisions every frame), and a ship to the scene.  This should help you understand a bit of what goes in OnLoadScene- the items loaded in OnLoadResources are placed and prepared for action!

OnLoadComplete

Finally, OnLoadComplete is called.  This where, once everything is loaded, you define all the movement and actions that make the game do what it should do.  For example, here is where you would put music.play(), or start any animations you want to begin when your game starts.

Hopefully, this will give you a good idea of how an AndEngine app flows!  Next time, we’ll be taking a look at different kinds of sprites, and which ones you want to use!

Advertisements
3 Comments
  1. Alejandro Huerta permalink

    This is a really good start for beginners like myself, but I feel there are many things left unexplained in this tutorial. For instance, you don’t explain the TextureRegionFactory, from what I can tell there is no .setAssetBasePath(String); maybe I have a different AndEngine version? FontFactory and SoundFactory do have this method.

    • Alejandro, I hope the guide was helpful! You’re right- this is something that hasn’t been in every version of AndEngine. I’ve tested each of these in multiple versions- including the latest- and haven’t had any trouble, but I’ll add a bit of information on how to move forward if using a version in which it isn’t present. I understand that there’s way more that I could explain in the course of this guide- however, the Getting Started section is really meant to be just enough to get started- not enough to really understand how everything works. I’m hoping that once I get past the basics, I can take a bit more in-depth look at things.

      • Alejandro Huerta permalink

        I couldn’t seem to duplicate your results with the latest but managed to get it working with a BitmapTextureAtlas and using the BitmapTextureAltasTextureRegionFactory, which does have the setAssetBasepath(String). Maybe I did something wrong but thanks for getting me started!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: