AndEngine的第一个程序HelloWorld(一)

2014-11-24 09:12:22 · 作者: · 浏览: 0

AndEngine的环境搭建好后,只运行Samples是远远不够的,要想真正了解如何使用这个框架,还是需要自己动手写写代码。

先从简单的HelloWorld开始。

目标:使用一张图片作为背景,并在屏幕中央显示“Hello World !”文字。

1.新建一个Android工程,设置工程属性,让工程引用AndEngine工程。

2.让工程的主Activity继承SimpleBaseGameActivity类。并实现基类中的几个方法:

[java]
public EngineOptions onCreateEngineOptions();
public void onCreateResources();
public Scene onCreateScene();
这个类的全部代码如下:
[java]
package com.example.testandeng1;

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.Entity;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.ui.activity.SimpleBaseGameActivity;

import android.graphics.Color;
import android.opengl.GLES20;

public class MainActivity extends SimpleBaseGameActivity {
public static final int CAMERA_WIDTH = 800;
public static final int CAMERA_HEIGHT = 480;

private static final int LAYER_COUNT = 2;

private static final int LAYER_BACKGROUND = 0;
private static final int LAYER_TEXT = LAYER_BACKGROUND + 1;

private Scene mScene;

private Font mFont;
private BitmapTextureAtlas mBackgroundTexture;
private ITextureRegion mBackgroundTextureRegion;

private Text mHelloText;

public EngineOptions onCreateEngineOptions() {
Camera mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
final EngineOptions engineOptions = new EngineOptions(true,
ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(
CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
return engineOptions;
}

@Override
public void onCreateResources(){
/* Load the font we are going to use. */
FontFactory.setAssetBasePath("font/");
this.mFont = FontFactory.createFromAsset(this.getFontManager(),
this.getTextureManager(), 512, 512, TextureOptions.BILINEAR,
this.getAssets(), "GOTHIC.TTF", 32, true, Color.WHITE);
this.mFont.load();

BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("img/");
/* Load all the textures this game needs. */
this.mBackgroundTexture = new BitmapTextureAtlas(
this.getTextureManager(), 800, 480);
this.mBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(this.mBackgroundTexture, this, "android.png",
0, 0);
this.mBackgroundTexture.load();
}

@Override
public Scene onCreateScene(){
this.mScene = new Scene();
for (int i = 0; i < LAYER_COUNT; i++) {
this.mScene.attachChild(new Entity());
}

/* No backgro