Trng Thanh Anh Tun Email:tuanatt@nahi.vn Mc lc 1. LM TH NO LM 1 GAME ? CCH G TT NHT LM GAME ? ............................................................................. 3 2. BAO LU TH S HON THNH XONG 1 GAME ? .................................................................................................................... 3 3. TI SAO LI PHI S DNG ANDENGINE M KHNG PHI 1 ENGINE NO KHC ? ........................................................ 3 4. NHNG BC U TIN TRONG LP TRNH GAME VI ANDENGINE (GLES2): ............................................................... 3 5. CC EXTENTIONS V EXAMPLE CA ANDENGINE ................................................................................................................ 5 6. NHNG VN CHNH TRONG ANDENGINE ........................................................................................................................... 7 7. XY DNG CC THNH PHN TO NN 1 GAME (GLES2) .............................................................................................. 9 8. XY DNG CC THNH PHN TO NN 1 GAME (GLES1) ............................................................................................ 16
3
Trng Thanh Anh Tun Email:tuanatt@nahi.vn 1. Lm th no lm 1 game ? Cch g tt nht lm game ? tht s l 1 vn kh tr li v vit 1 game s dng trn nhiu platform th cn rt nhiu cng sc b ra thc hin v cn c 1 s kin nhn nht nh thc hin.Nn n khng phi l cch lm tt nht.Trong bi vit ny s s dng 1 Engine gip vic thc hin 1 game tr nn d dng thc hin hn. 2. Bao lu th s hon thnh xong 1 game ? Ty theo su ca tr chi m c th chim c nm tri lp trnh hoc ch tn vi ngy thc hin nu n khng c honh trng trong game. 3. Ti sao li phi s dng AndEngine m khng phi 1 Engine no khc ? C rt nhiu Engine dng lm 1 game s dng nhiu nht Vit Nam n c l E3Droid hoc AndEngine hoc libgdx ,nhng ti sao li nn s dng AndEngine ?.Chnh v s thun tin thc hin 1 cch d dng lm game v n cho bn 1 s t do s dng cc ngun ti nguyn m Android v Java cung cp thc hin . l 1 framework cho bn nhiu s t do nhiu hn nhng framework khc nhng bn cng cn phi b ra cht t cng sc na nu mun sn phm bn lm ra n s l tt nht .C nhng Framework hn ch s t do tong tc ca bn li nn khin cho game rt n gin trong cch chi v d nh libgdx v cn 1 phn quan trng na l cng ng lm game hin ti Vit Nam th AndEngine ang pht trin rt mnh. 4. Nhng bc u tin trong lp trnh game vi AndEngine (GLES2): Ci t v chun b nhng yu cu v phn mm o JDK : Tt nht nn ci t phin bn mi nht c s h tr tt nht ti y o ADT : S dng IDE ca pht trin Android ti y o AndEngine Source : B th vin download ti y , bn c th xem cc example v cc tnh nng m b framework ny h tr ti y Example u tin : Hello world vi AndEngine GLES2 Import th vin AndEngine :
To Project HelloWorld v import th vin AndEngine : 4
Trng Thanh Anh Tun Email:tuanatt@nahi.vn
Add image HelloWorld vo trong th mc asset ti hnh ti y Activity s dng AndEngine u phi extend li SimpleBaseGameActivity hoc BaseGameActivity. Khai bo 2 bin quan trng : private ITexture mHelloWorldTexture; private ITextureRegion mHelloWorldTextureRegion; Kch thc vng hin th : private static final int CAMERA_WIDTH = 800; private static final int CAMERA_HEIGHT = 480; Trong phung thc onCreateEngineOptions : final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);//Qun l cu hnh mn hnh return new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); Trong phung thc onCreateResources: //S dng resource ang c trong th mc assets this.mHelloWorldTexture = new AssetBitmapTexture(this.getTextureManager(), this.getAssets(), "helloworld.png"); this.mHelloWorldTextureRegion = TextureRegionFactory.extractFromTexture( this.mHelloWorldTexture); this.mHelloWorldTexture.load(); Trong phung thc onCreateScene: //Qun l tt c nhng g bn v trn vng hin th this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); 5
Trng Thanh Anh Tun Email:tuanatt@nahi.vn 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); // 1 i tng hnh l 1 sprite trong AndEngine return scene; Kt qu ca example trn :
5. Cc Extentions v Example ca AndEngine u tin n vi AndEngine ta c 1 bt li l khng c document cho framework ny,nhng b li ta c 1 lng example rt ln vit 1 game theo mun.Phn ny s hung dn bn cch thm cc Extention ca AndEngine . Download Project Example ti y Download Project Extention: 1. AndEngine 2. AndEngineAugmentedRealityExtension 3. AndEngineMODPlayerExtension 4. AndEngineSVGTextureRegionExtension 5. AndEnginePhysicsBox2DExtension 6. AndEngineMultiplayerExtension 7. AndEngineTMXTiledMapExtension 8. AndEngineScriptingExtension 9. AndEngineCocosBuilderExtension 10. AndEngineLiveWallpaperExtension 11. AndEngineCocosBuilderExtensionCCRotatingSpriteExtension(sm4) 12. AndEngineCocosBuilderExtensionCCRotatingSpriteExtension(nicolasgramlich) 6
Trng Thanh Anh Tun Email:tuanatt@nahi.vn
Sau khi import vo ta nn Clean All Project . V fix nhng li sau trc khi xem cc example ca AndEngine : 1. Li ca SVG Extension : Add unimplemented cc phung thc cn thiu,bi v SVG extension khng c trong version AnchorCenter. 2. Li ca Scripting Extension : .S dng search -> file sau replace import org.andengine.util.color.Color; thnh import org.andengine.util.adt.color.Color; .Xa class RectangularShapeProxy bi v n khng s dng trong version AnchorCenter. 3. Li ca AndEngine Examples : Cui cng ta s tip tc fix li i vi AndEngineExample ,danh sch li nh sau : Search Replace import org.andengine.extension.multiplayer.protocol import org.andengine.extension.multiplayer import org.andengine.extension.multiplayer.exception.BluetoothException; import org.andengine.util.exception.BluetoothException; 7
Trng Thanh Anh Tun Email:tuanatt@nahi.vn import org.andengine.entity.particle.modifier.ExpireParticleInitializer; import org.andengine.entity.particle.initializer.ExpireParticleInitializer; import org.andengine.extension.multiplayer.util.IPUtils; import org.andengine.util.IPUtils; import org.andengine.extension.multiplayer.util.WifiUtils; import org.andengine.util.WifiUtils; if(!AndEngine.isDeviceSupported()) { if(!AndEngine.isDeviceSupported(this)) { Cc IOExceltion bo li ta chuyn thnh Exception. Cc li th vin cn li , ta remove dng Import th vin v add li i vi cc hm cn th vin. Run Appliation xem thnh qu . 6. Nhng vn chnh trong AndEngine Camera : Camera trong game n xc nh mn hnh hin th v trnh by cho ngi chi thy ,n ging nh 1 my quay phim trong 1 khng gian 2 chiu v ta c th tng tc phng to hoc thu nh , iu khin cc vt th tung tc vi game. N xc nh mt hnh ch nht vi chiu di v chiu rng xc nh trc v ln mn hnh. C th tt c cc th trong game s c nhn thy trn camera hoc camera ch hin th mt phn ca khung cnh, bn phi di chuyn camera nhn thy cc phn cn li (Boundcamera) . Hoc mt camera c th phng to, thu nh hoc cun gi l ZoomCamera. Scene : N cha tt c cc i tng m bn v trn mn hnh. N ging nh mt t giy, trn bn c th v tt c cc hnh, cp nht chng v c th cha cc t giy khc. 1 game ging nh 1 b phim c trnh chiu n ngi xem m trong n bao gm cc hot cnh v cc hnh ng din ra trong 1 b phim ,nhng cnh ny c bin tp li v sp xp vi nhau 1 cch c nh n s to thnh 1 b phim hon chnh . Layer : Cc scene l tp hp cc layer ha n nm chng ln nhau ging nh cc cel c s dng lm phim hot hnh nh hi xa ,ngoi ra cc layer cn to hiu ng 2 1 /2D. Sprite : N c v nh cc din vin trong 1 b phim ,n c th l 1 con ngi hoc 1 vt,n c th di chuyn hoc khng v n c th di chuyn trong cc scene ,cu trc ca 1 sprite bao gm tp hp cc hnh nh sprite c gi l sprite sheet. Entity : L nhng Object s v cc bc nh ca bn ln scene. C th mt bc nh tnh (Sprite), mt bc nh ng (AnimatedSprite), hoc mt bc nh c nhiu bc nh con trong n (TitledSprite). Trong AndEngine cc entity(thc th) l nhng th c v hoc hin th trn mn hnh n chnh l cc sprite v d nh 1 vin gch hoc 1 i tung hnh hc hoc 1 dng k c v trn mn hnh.Tt c cc thc th u c cc thuc tnh nh mu sc, co gin,gc xoay, v tr t v n c th chnh sa li gi tr nu mnh mun. Modifier : Modifier c th thay i thuc tnh ca cc Entity v n rt mnh nht l trong AndEngine .N c th s dng trn bt k Entity no v n s c thay i v cp nht ngay lp tc trong khi game vn ang din ra .Trong 1 game chng TATT modifier thng xuyn s dng to cc hiu ng vi Sprite v Entity khc. 8
Trng Thanh Anh Tun Email:tuanatt@nahi.vn Texture : Texture Region : Engine : Trong game c nhiu tin trnh nh chy song song. Engine s qun l tt c cc tin trnh . Ci ny bn khng cn phi quan tm nhiu v andengine s lm vic . BaseGameActivity : L 1 lp m rng ca lp Activity trong android,n l c s cho mi scene trong game ,n lm tt c cc cng vic ca chung ca tt c cc scene v cc thit lp trong engine ca game ,i vi cc cm bin v vng i ca mi Activity. Physics Connector : AndEngine bao gm c tnh nng vt l c bn trong b engine,Box2D Physics Engine l phn m rng ln vo nhng kh nng ny.Chng kt ni cc i tng trong AndEngine vi Box2D thng qua kt ni vt l.Nu trong game ca bn khng s dng Box2D th game se khng c bt c tng tc vt l thng qua kt ni vt l. Box2D Physics Engine : AndEngine bao gm b m ngun m Jbox2 n l 1 cng ca engine Box2D vt l.N c th s dng m phng tng tc thc t ca cc i tng trong nhng cc sau : +Trng lc (Gravity) +Stable stacking +M phng vt l ca cc c quan trong c th
9
Trng Thanh Anh Tun Email:tuanatt@nahi.vn 7. Xy dng cc thnh phn to nn 1 game (GLES2) 3 thnh phn quan trng ca 1 Activity k tha t SimpleBaseGameActivity:
Mi 1 Activity s c 1 vng hin th hot cnh (Scene) ring v tt c c qun l bng mEngine. 7.1 Cnh nn (Background) : Ty theo th loi game m ngi s dng s lm cnh nn cho ph hp,c chia ra lm 3 loi : +Repeating Spire Background (Cnh nn c khi to full mn hnh bng Spire c lp theo chiu X v Y): 1.Method onCreateEngineOptions() : Khai bo mc nh nh trn 2.Method onCreateResources() :
// Load nh t th mc Asset,loi Texture l Repeating this.mBackgroundTexture = new AssetBitmapTexture(this.getTextureManager(), this.getAssets(), "gfx/background_grass.png", TextureOptions.REPEATING_NEAREST); this.mBackgroundTexture.load();
final ITextureRegion backgroundTextureRegion = TextureRegionFactory.extractFromTexture(this.mBackgroundTexture);
// Thc hin repeat theo chiu cao v chiu rng ca camera this.mGrassBackground = new RepeatingSpriteBackground(CAMERA_WIDTH,CAMERA_HEIGHT, backgroundTextureRegion,this.getVertexBufferObjectManager()); @Override public EngineOptions onCreateEngineOptions() { // Khi to vng quan st (Camera) : Mc nh mi 1 Activity s c chung phn khai bo,chiu rng,chiu cao,nh hng hin th s ty theo ngi s dng xt 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 { // Khi to ngun ti nguyn t Asset/Drawable/Folder bt k/Load t b nh ... } @Override public Scene onCreateScene() { // Khi to vng hin th hot cnh (Scene) bao gm cc Spire/Particle/Button Sprite... ... }
10
Trng Thanh Anh Tun Email:tuanatt@nahi.vn 3.Method onCreateScene() :
Source nh km RepeatingBackground.zip
+AutoParallax Background (To cnh nn di chuyn): 1.Method onCreateEngineOptions() : Khai bo mc nh nh trn 2.Method onCreateResources() :
3.Method onCreateScene() :
final Scene scene = new Scene(); scene.setBackground(this.mGrassBackground); this.mParallaxLayerBackTexture = new AssetBitmapTexture(this.getTextureManager(), this.getAssets(), "gfx/parallax_background_layer_back.png"); this.mParallaxLayerBackTextureRegion = TextureRegionFactory.extractFromTexture(this.mParallaxLayerBackTexture); this.mParallaxLayerBackTexture.load();
this.mParallaxLayerMidTexture = new AssetBitmapTexture(this.getTextureManager(), this.getAssets(), "gfx/parallax_background_layer_mid.png"); this.mParallaxLayerMidTextureRegion = TextureRegionFactory.extractFromTexture(this.mParallaxLayerMidTexture); this.mParallaxLayerMidTexture.load();
this.mParallaxLayerFrontTexture = new AssetBitmapTexture(this.getTextureManager(), this.getAssets(), "gfx/parallax_background_layer_front.png"); this.mParallaxLayerFrontTextureRegion = TextureRegionFactory.extractFromTexture(this.mParallaxLayerFrontTexture); this.mParallaxLayerFrontTexture.load(); final Sprite parallaxLayerBackSprite = new Sprite(0, 0, this.mParallaxLayerBackTextureRegion, vertexBufferObjectManager); parallaxLayerBackSprite.setOffsetCenter(0, 0); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, parallaxLayerBackSprite));
final Sprite parallaxLayerMidSprite = new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerMidTextureRegion.getHeight() - 80, this.mParallaxLayerMidTextureRegion, vertexBufferObjectManager); parallaxLayerMidSprite.setOffsetCenter(0, 0); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-5.0f, parallaxLayerMidSprite));
final Sprite parallaxLayerFrontSprite = new Sprite(0, 0, this.mParallaxLayerFrontTextureRegion, vertexBufferObjectManager); parallaxLayerFrontSprite.setOffsetCenter(0, 0); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-10.0f, parallaxLayerFrontSprite)); 11
Trng Thanh Anh Tun Email:tuanatt@nahi.vn Source nh km ParallaxBackground.zip
+TMX TiledMap (To Background t TiledMap):Thun li l to map d dng do s dng Tool Source nh km TMXTiledBackground.zip
7.2 Cc i tng : 7.2.1 ANIMATE SPRITE : Cng nh Sprite nhng Animate Sprite c thm chc nng hot nh bng cch chia 1 tm nh ra thnh nhiu vng v duyt tng vng ca tm nh khin ta thy nh chuyn ng. VD : Vi tm nh bn di hot cnh ta chia tm nh ra 12 vng:
1.Method onCreateEngineOptions() : Khai bo mc nh nh trn 2.Method onCreateResources() : TiledTextureRegion mSnapdragonTextureRegion mSnapdragonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "snapdragon_tiled.png", 4, 3); 3.Method onCreateScene() : final AnimatedSprite snapdragon = new AnimatedSprite(CAMERA_WIDTH * 0.33f, CAMERA_HEIGHT * 0.66f, this.mSnapdragonTextureRegion, this.getVertexBufferObjectManager()); snapdragon.animate(100); //Di chuyn sang vng khc vi tr l 100ms scene.attachChild(snapdragon); Source nh km AnimatedSprites.zip
7.2.2 BUTTON SPRITE : Vi nhng i tng khng cn n chuyn ng th Button Sprite l hp l nht v n s hn ch c ti nguyn s dng tm nh m khng cn hot cnh,cc s kin trong GLES2 i vi Button Sprite gn nh tng t nh Widget Button ca Android nhng khc i vi s kin Long Click,i vi phn ny phi vit ring ra. 12
Trng Thanh Anh Tun Email:tuanatt@nahi.vn Chng ta k l nu nh lm 1 button th n s c hover effect v over effect,Sprite hoc l Animated Sprite s khng c 2 phn ny cn mun thc hin th ta s khi to 2 Sprite hoc 2 Animated Sprite v khi Click ln m gi lu th s Visible = true Sprite hoc Animated Sprite Hover ln th ra th Visible = false Sprite hoc Animated Sprite Hover 1.Method onCreateEngineOptions() : Khai bo mc nh nh trn 2.Method onCreateResources() : this.mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(this.getTextureManager(), 512, 512); this.mButtonNormalTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "button_normal.png");//Button trng thi bnh thng this.mPressedTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "button_pressed.png");");//Button trng thi khi click ln this.mDisabledTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "button_disabled.png");//Button trng thi khi Enable = false try { this.mBuildableBitmapTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0)); this.mBuildableBitmapTextureAtlas.load(); } catch (TextureAtlasBuilderException e) { Debug.e(e); } 3.Method onCreateScene() : buttonSprite = new ButtonSprite(centerX, centerY, this.mButtonNormalTextureRegion, this.mPressedTextureRegion, this.mDisabledTextureRegion, this.getVertexBufferObjectManager(), this); ");//C 3 trng thi ca 1 button s c gom li cho 1 Button Sprite Source nh km ButtonSprite.zip
7.2.3 SPRITE : i vi nhng yu cu nh th hin 1 i tng tnh no m khng quan trng lm trong game vd nh cy ci hoc my tri thuyn tri xe chy .v.v th Sprite l s ph hp nht thc hin. 1.Method onCreateEngineOptions() : Khai bo mc nh nh trn 2.Method onCreateResources() : this.mFaceTexture = new AssetBitmapTexture(this.getTextureManager(), this.getAssets(), "gfx/face_box.png"); this.mFaceTextureRegion = TextureRegionFactory.extractFromTexture(this.mFaceTexture); this.mFaceTexture.load(); 3.Method onCreateScene() : 13
Trng Thanh Anh Tun Email:tuanatt@nahi.vn final Sprite sprite = new Sprite(centerX, centerY, this.mFaceTextureRegion, this.getVertexBufferObjectManager()); scene.attachChild(sprite); Source nh km Sprite.zip
7.2.4 PARTICLE SYSTEM : H thng ht bn thn cng l cc Sprite km theo cc chuyn ng theo 1 Path vi thi gian sng ca mi ht c nh km theo mi ht tit kim b nh mi khi s dng,i vi nhng yu cu nh lm tuyt ri,hoa ri,l ri,hiu ng la,nc chy .v.v th Particle System l 1 la chn ph hp nht. 1.Method onCreateEngineOptions() : Khai bo mc nh nh trn 2.Method onCreateResources() : this.mParticleTexture = new AssetBitmapTexture(this.getTextureManager(), this.getAssets(), "gfx/particle_fire.png", TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mParticleTextureRegion = TextureRegionFactory.extractFromTexture(this.mParticleTexture); this.mParticleTexture.load(); 3.Method onCreateScene() : final BatchedPseudoSpriteParticleSystem particleSystem = new BatchedPseudoSpriteParticleSystem(new PointParticleEmitter(0, ParticleSystemCoolExample.CAMERA_HEIGHT), 6, 10, 200, this.mParticleTextureRegion,this.getVertexBufferObjectManager()); particleSystem.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE);
//Mu s chuyn t mu no sang mu no theo h mu RBG particleSystem.addParticleModifier(new ColorParticleModifier<Entity>(0.0f, 11.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f));
particleSystem.addParticleModifier(new AlphaParticleModifier<Entity>(4.5f, 11.5f, 1.0f, 0.0f)); Source nh km ParticleSystem.zip
7.2.5 TEXT : Cc thng ip hin th theo dng text v c th sa i do ngi s dng th ch duy nht c Text mi c th lm c. 1.Method onCreateEngineOptions() : Khai bo mc nh nh trn 2.Method onCreateResources() : //nh ng dn cha Font cn s dng FontFactory.setAssetBasePath("font/");
//Khai bo kch thc,mu sc,loi font cn s dng this.mDroidFont = FontFactory.createFromAsset(this.getFontManager(), this.getTextureManager(), 256, 256, TextureOptions.BILINEAR, this.getAssets(), "Droid.ttf", FONT_SIZE, true, Color.BLACK); this.mDroidFont.load();3.Method onCreateScene() : 3.Method onCreateScene() : final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager();
//Set text v hin th ln Scene vi kiu Font c nh ngha nh trn scene.attachChild(new Text(centerX, 400, this.mDroidFont, "Droid Font", vertexBufferObjectManager));
//Cp nht text lin tc scene.registerUpdateHandler(new TimerHandler(1 / 10.0f, true, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { textExample.setText(String.format("FPS: %.2f", fpsCounter.getFPS())); } })); Source nh km TextExample.zip
15
Trng Thanh Anh Tun Email:tuanatt@nahi.vn 7.3 Tng tc vt l : Tng tc vt l ng vai tr quan trng trong 1 game gip ngi dng tng tc trc tip vi cc Sprite gip game thm sinh ng v hp dn,c nhiu phn trong AndEngine Physics,nhng y l nhng phn ct li nht. 7.3.1 XC NH VA CHM GIA 2 SPRITE : 1.Method onCreateScene() : scene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() { } @Override public void onUpdate(final float pSecondsElapsed) { // CollidesWith : Xc nh va chm gia vt th A v vt th B if(centerRectangle.collidesWith(sprite)) { centerRectangle.setColor(1, 0, 0); } else { centerRectangle.setColor(0, 1, 0); } ... } }); Source nh km CollisionDetection.zip
7.3.2 TOUCH AND DRAG : 1.Method onCreateScene() : final Sprite sprite = new Sprite(centerX, centerY, this.mFaceTextureRegion, this.getVertexBufferObjectManager()) { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2); return true; } }; Source nh km TouchAndDrag.zip
7.4 Scene Manager : Trong 1 game,mi 1 cnh hin trn mn hnh l 1 scene bao gm cc hot cnh,nh vy nu nhiu scene th vic qun l v chuyn i qua li gia cc scene s nh th no,do ta s cn 1 Scene Manager qun l tt c cc Scene. 16
Trng Thanh Anh Tun Email:tuanatt@nahi.vn Trong Example bn di s demo vic load 1 game t Scene Splash Screen xong s n Scene Menu Screen,vic chuyn gia cc Scene s mt hn khi dng "sceneManager.setCurrentScene(AllScenes.MENU);. Source nh km SceneManager.zip
8. Xy dng cc thnh phn to nn 1 game (GLES1 ch nn tham kho thm) Chng ta s ly th vin c build sn s dng khi xy dng game, file bn di ang s dng AndEngine GLES1:
8.1 Dng nh nn (Background): public class MainActivity extends BaseGameActivity {
// Khai bo thm 2 bin quan trng private Camera MyCamera;// Bin ny thng cu hnh mn hnh private Scene MyScene;// Qun l nhng g bn v.
private int WIDTH = 320; private int HEIGHT = 480;
@Override public Engine onLoadEngine() { // Khi to vng hin th l 320*480 this.MyCamera = new Camera(0, 0, WIDTH, HEIGHT); // Yu cu mn hnh hin th nm ngang th ScreenOrientation.LANDSCAPE Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(WIDTH, HEIGHT), this.MyCamera)); return engine; } @Override public void onLoadResources() {} @Override public Scene onLoadScene() { MyScene = new Scene(); // Dng mu nh nn t h mu RGB MyScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); return MyScene; 17
Trng Thanh Anh Tun Email:tuanatt@nahi.vn }
@Override public void onLoadComplete() {} } Source nh km AndEngine_Test01.rar
8.2 Thao tc vi hin th text: public class MainActivity extends BaseGameActivity {
// Khai bo thm 2 bin quan trng private Camera MyCamera;// Bin ny thng cu hnh mn hnh private Scene MyScene;// Qun l nhng g bn v.
private int WIDTH = 320;// Chiu rng vng hin th private int HEIGHT = 480;// Chiu cao vng hin th
private BitmapTextureAtlas mFontTexture;// Lu font vo b nh private Font mFont;// Dng lu li font
@Override public Engine onLoadEngine() { // Khi to vng hin th l 320*480 this.MyCamera = new Camera(0, 0, WIDTH, HEIGHT); // Yu cu mn hnh hin th nm ngang th ScreenOrientation.LANDSCAPE Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(WIDTH, HEIGHT), this.MyCamera)); return engine; }
@Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); // To font mc nh v style l ch m, c ch 14 mu en this.mFont = new Font(this.mFontTexture, Typeface.create( Typeface.DEFAULT, Typeface.BOLD), 14, true, Color.BLACK); 18
Trng Thanh Anh Tun Email:tuanatt@nahi.vn // Load this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.mEngine.getFontManager().loadFont(this.mFont); }
@Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger());
MyScene = new Scene(); MyScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));// t mu nn
// Khai bo 3 hin text. Dng HorizontalAlign cn l. final Text textCenter = new Text(20, 60, this.mFont, "Text A", HorizontalAlign.CENTER); final Text textLeft = new Text(20, 200, this.mFont, "Text B", HorizontalAlign.LEFT); final Text textRight = new Text(20, 340, this.mFont, "Text C", HorizontalAlign.RIGHT);
// Hin th ln mn hnh MyScene.attachChild(textCenter); MyScene.attachChild(textLeft); MyScene.attachChild(textRight);
return MyScene; }
@Override public void onLoadComplete() {}
} Source nh km AndEngine_Test02.rar
8.3 Cp nht game thi gian thc : 19
Trng Thanh Anh Tun Email:tuanatt@nahi.vn public class MainActivity extends BaseGameActivity {
//Khai bo thm 2 bin quan trng private Camera MyCamera;//Bin ny thng cu hnh mn hnh private Scene MyScene;//Qun l nhng g bn v.
private int WIDTH = 320;//Chiu rng vng hin th private int HEIGHT = 480;//Chiu cao vng hin th
private BitmapTextureAtlas mFontTexture;//Lu font vo b nh private Font mFont;//Dng lu li font private int dem = 0;
@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; }
@Override public Engine onLoadEngine() { //Khi to vng hin th l 320*480 this.MyCamera = new Camera(0, 0, WIDTH, HEIGHT); //Yu cu mn hnh hin th nm ngang th ScreenOrientation.LANDSCAPE Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(WIDTH, HEIGHT), this.MyCamera)); return engine; }
@Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); //To font mc nh v style l ch m, c ch 14 mu en this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 14, true, Color.BLACK); //Load this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.mEngine.getFontManager().loadFont(this.mFont); 20
Trng Thanh Anh Tun Email:tuanatt@nahi.vn }
@Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger());
MyScene = new Scene(); MyScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));//t mu nn
//Khai bo ChangeableText dng hin th thi gian theo tng giy final ChangeableText textchange = new ChangeableText(10, 10, this.mFont, "", 10);//Ti a hin th 10 k t MyScene.attachChild(textchange); //Cp nht (coi nh vng lp hot cnh) MyScene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() {} //Mun cp nht ci g th cho vo y @Override public void onUpdate(float pSecondsElapsed) { try { //Tm dng cp nht trong 1s Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Cp nht li nhng g bn cn v li lin tc dem++; textchange.setText(String.valueOf(dem));//C sau 1s ta li hin th m } }); return MyScene; } @Override public void onLoadComplete() {} } Source nh km AndEngine_Test03.rar
21
Trng Thanh Anh Tun Email:tuanatt@nahi.vn 8.4 To 1 sprite : Thm 1 nh vo th mc asset : Pic 1 : ball.png
on code chnh trong BaseGameActivity public class MainActivity extends BaseGameActivity { // Khai bo thm 2 bin quan trng private Camera MyCamera;// Bin ny thng cu hnh mn hnh private Scene MyScene;// Qun l nhng g bn v.
private int WIDTH = 320;// Chiu rng vng hin th private int HEIGHT = 480;// Chiu cao vng hin th
private BitmapTextureAtlas bitmapTextureAtlas;// Lu nh trong b nh private TextureRegion textureRegion;// Lu khi load nh private Sprite sprite;// Sprite qu bng
@Override public Engine onLoadEngine() { // Khi to vng hin th l 320*480 this.MyCamera = new Camera(0, 0, WIDTH, HEIGHT); // Yu cu mn hnh hin th nm ngang th ScreenOrientation.LANDSCAPE Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(WIDTH, HEIGHT), this.MyCamera)); return engine; }
@Override public void onLoadResources() { // Khai bo vng lu tr nh c kch thc 256,256. y l ci kh nht // . S gii thch sau. this.bitmapTextureAtlas = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); // Load nh 22
Trng Thanh Anh Tun Email:tuanatt@nahi.vn this.textureRegion = BitmapTextureAtlasTextureRegionFactory .createFromAsset(this.bitmapTextureAtlas, this, "ball.png", 0, 0); mEngine.getTextureManager().loadTextures(this.bitmapTextureAtlas); }
@Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger());
MyScene = new Scene(); MyScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));// t mu nn
// t sprite ti v tr x = 100,y = 100 this.sprite = new Sprite(100, 100, this.textureRegion); MyScene.attachChild(sprite);// Add vo MyScene
// Cp nht (coi nh vn lp hot cnh) MyScene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() { // TODO Auto-generated method stub }
boolean chuyen = false;
// Mun cp nht ci g th cho vo y @Override public void onUpdate(float pSecondsElapsed) { try { // Tm dng cp nht trong 10 ms Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Di chuyn sang phi if (!chuyen) { sprite.setPosition(sprite.getX() + 5, 100); if (sprite.getX() > 200)// Vt qu gii hn th cho di 23
Trng Thanh Anh Tun Email:tuanatt@nahi.vn // chuyn ngc li chuyen = true; } else { sprite.setPosition(sprite.getX() - 5, 100); if (sprite.getX() < 10) chuyen = false; } } });
return MyScene; }
@Override public void onLoadComplete() {} } Source nh km AndEngine_Test04.rar
8.5 Tung tc vi giao din v sprite : Thm 1 nh vo th mc asset : Pic 1 : ball.png
on code chnh trong BaseGameActivity public class MainActivity extends BaseGameActivity {
// Khai bo thm 2 bin quan trng private Camera MyCamera;// Bin ny thng cu hnh mn hnh private Scene MyScene;// Qun l nhng g bn v.
private int WIDTH = 320;// Chiu rng vng hin th private int HEIGHT = 480;// Chiu cao vng hin th
private BitmapTextureAtlas bitmapTextureAtlas;// Lu nh trong b nh 24
Trng Thanh Anh Tun Email:tuanatt@nahi.vn private TextureRegion textureRegion;// Lu khi load nh private Sprite sprite;// Sprite qu bng
/** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }
@Override public Engine onLoadEngine() { // Khi to vng hin th l 320*480 this.MyCamera = new Camera(0, 0, WIDTH, HEIGHT); // Yu cu mn hnh hin th nm ngang th ScreenOrientation.LANDSCAPE Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(WIDTH, HEIGHT), this.MyCamera)); return engine; }
@Override public void onLoadResources() { // Khai bo vng lu tr nh c kch thc 256,256. y l ci kh nht // . S gii thch sau. this.bitmapTextureAtlas = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); // Load nh this.textureRegion = BitmapTextureAtlasTextureRegionFactory .createFromAsset(this.bitmapTextureAtlas, this, "ball.png", 0, 0); mEngine.getTextureManager().loadTextures(this.bitmapTextureAtlas); }
@Override 25
Trng Thanh Anh Tun Email:tuanatt@nahi.vn public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger());
MyScene = new Scene(); MyScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));// t mu nn
// =================LNG NGHE S KIN CHM VO MN HNH MyScene======================= // Bt s kin khi chm vo MyScene MyScene.setTouchAreaBindingEnabled(true);// cho php lng nghe MyScene.setOnSceneTouchListener(new IOnSceneTouchListener() { public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { System.out.println("MyScene onSceneTouchEvent: chm vo mn hnh"); System.out.println("Ta X = " + pSceneTouchEvent.getX()); System.out.println("Ta Y = " + pSceneTouchEvent.getY());
// Khi chm vo mn hnh ta di chuyn sprite theo t y. sprite.setPosition(sprite.getX(), pSceneTouchEvent.getY()); return true; } }); // =====================LNG NGHE S KIN KHI CHM VO SPRITE========================== // t sprite ti v tr x = 100,y = 100 this.sprite = new Sprite(100, 100, this.textureRegion) { // Lng nghe s kin khi chm vo sprite @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN) { System.out.println("Sprite onAreaTouched: chm vo sprite"); System.out.println("Ta X = " + pTouchAreaLocalX); System.out.println("Ta Y = " + pTouchAreaLocalY); } return true; } }; MyScene.attachChild(sprite);// Add vo MyScene MyScene.registerTouchArea(sprite);// Phi ng k l cho php sprite ny c lng nghe s kin // ====================================================================================== // Cp nht (coi nh vn lp hot cnh) 26
Trng Thanh Anh Tun Email:tuanatt@nahi.vn MyScene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() { // TODO Auto-generated method stub }
boolean chuyen = false;
// Mun cp nht ci g th cho vo y @Override public void onUpdate(float pSecondsElapsed) { try { // Tm dng cp nht trong 10 ms Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Di chuyn sang phi if (!chuyen) { sprite.setPosition(sprite.getX() + 5, sprite.getY()); if (sprite.getX() > 200)// Vt qu gii hn th cho di chuyn ngc li chuyen = true; } else { sprite.setPosition(sprite.getX() - 5, sprite.getY()); if (sprite.getX() < 10) chuyen = false; } } });
return MyScene; }
@Override public void onLoadComplete() {} } Source nh km 27
Trng Thanh Anh Tun Email:tuanatt@nahi.vn AndEngine_Test05.rar
8.6 To sprite chuyn ng t 1 nh : Thm 1 nh vo th mc asset : Pic 1 : sprite.png
on code chnh trong BaseGameActivity public class MainActivity extends BaseGameActivity { //Khai bo thm 2 bin quan trng private Camera MyCamera;//Bin ny thng cu hnh mn hnh private Scene MyScene;//Qun l nhng g bn v.
private int WIDTH = 320;//Chiu rng vng hin th private int HEIGHT = 480;//Chiu cao vng hin th
private BitmapTextureAtlas bitmapTextureAtlas;//Lu nh trong b nh private TiledTextureRegion tiledTextureRegion;//Lu khi load nh private AnimatedSprite animatedSprite ;//AnimatedSprite
/** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }
@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); 28
Trng Thanh Anh Tun Email:tuanatt@nahi.vn return true; }
@Override public Engine onLoadEngine() { //Khi to vng hin th l 320*480 this.MyCamera = new Camera(0, 0, WIDTH, HEIGHT); //Yu cu mn hnh hin th nm ngang th ScreenOrientation.LANDSCAPE Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(WIDTH, HEIGHT), this.MyCamera)); return engine; }
@Override public void onLoadResources() { //Bc nh ch rng 512 v cao 512 nn ta khai bo theo ng kch thc tn b nh this.bitmapTextureAtlas = new BitmapTextureAtlas(512, 512, TextureOptions.BILINEAR); //S 4 y l 4 ct v 4 hng this.tiledTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.bitmapTextureAtlas, this, "sprite.png", 0, 0, 4, 4); this.mEngine.getTextureManager().loadTexture(this.bitmapTextureAtlas); }
@Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger());
MyScene = new Scene(); MyScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));//t mu nn
//=====================LNG NGHE S KIN CHM VO MN HNH MyScene=============================== //Bt s kin khi chm vo MyScene MyScene.setTouchAreaBindingEnabled(true);//cho php lng nghe MyScene.setOnSceneTouchListener(new IOnSceneTouchListener() { public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { System.out.println("Sprite onSceneTouchEvent: chm vo mn hnh"); System.out.println("Ta X = "+pSceneTouchEvent.getX()); System.out.println("Ta Y = "+pSceneTouchEvent.getY());
29
Trng Thanh Anh Tun Email:tuanatt@nahi.vn //Khi chm vo mn hnh ta di chuyn AnimatedSprite theo t y. animatedSprite.setPosition(animatedSprite.getX(), pSceneTouchEvent.getY()); return true; } }); //====================LNG NGHE S KIN KHI CHM VO ANIMATEDSPRITE============================= //t AnimatedSprite ti v tr x = 100,y = 100 this.animatedSprite = new AnimatedSprite(100, 100, this.tiledTextureRegion){ //Lng nghe s kin khi chm vo sprite @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){ System.out.println("AnimatedSprite onAreaTouched: chm vo animatedSprite"); System.out.println("Ta X = "+pTouchAreaLocalX); System.out.println("Ta Y = "+pTouchAreaLocalY); } return true; } }; animatedSprite.animate(100);//Sau 100milis ta s i bc nh MyScene.attachChild(animatedSprite);//Add vo MyScene MyScene.registerTouchArea(animatedSprite);//Phi ng k l cho php AnimatedSprite ny c lng nghe s kin //===================================================================================== //Cp nht (coi nh vng lp hot cnh) MyScene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() { // TODO Auto-generated method stub }
boolean chuyen = false; //Mun cp nht ci g th cho vo y @Override public void onUpdate(float pSecondsElapsed) { try { //Tm dng cp nht trong 10 ms Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block 30
Trng Thanh Anh Tun Email:tuanatt@nahi.vn e.printStackTrace(); } //Di chuyn sang phi if(!chuyen){ animatedSprite.setPosition(animatedSprite.getX()+5, animatedSprite.getY()); if(animatedSprite.getX() > 200)//Vt qu gii hn th cho di chuyn ngc li chuyen = true; }else{ animatedSprite.setPosition(animatedSprite.getX()-5, animatedSprite.getY()); if(animatedSprite.getX() < 10) chuyen = false; } } }); return MyScene; } @Override public void onLoadComplete() {}
} Source nh km AndEngine_Test06.rar
8.7 To kt hp sprite chuyn ng v nh nn : Thm 1 nh vo th mc asset : Pic 1: sprite.png
Pic 2: ball.png 31
Trng Thanh Anh Tun Email:tuanatt@nahi.vn
on code chnh trong BaseGameActivity : public class MainActivity extends BaseGameActivity { //Khai bo thm 2 bin quan trng private Camera MyCamera;//Bin ny thng cu hnh mn hnh private Scene MyScene;//Qun l nhng g bn v.
private int WIDTH = 320;//Chiu rng vng hin th private int HEIGHT = 480;//Chiu cao vng hin th
private BitmapTextureAtlas bitmapTextureAtlas;//Lu nh trong b nh private TiledTextureRegion tiledTextureRegion;//Lu khi load nh private AnimatedSprite animatedSprite ;//AnimatedSprite
private RepeatingSpriteBackground mGrassBackground;//Khai bo i tng lm thc hin lp nh to cnh nn
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }
@Override public Engine onLoadEngine() { //Khi to vng hin th l 320*480 this.MyCamera = new Camera(0, 0, WIDTH, HEIGHT); //Yu cu mn hnh hin th nm ngang th ScreenOrientation.LANDSCAPE Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(WIDTH, HEIGHT), this.MyCamera)); return engine; }
@Override public void onLoadResources() { 32
Trng Thanh Anh Tun Email:tuanatt@nahi.vn //Bc nh ch rng 64 v cao 32 nn ta khai bo theo ng kch thc tn b nh this.bitmapTextureAtlas = new BitmapTextureAtlas(512, 512, TextureOptions.BILINEAR); //S 2 y l 2 ct. S 1 tc l c 1 hng this.tiledTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.bitmapTextureAtlas, this, "sprite.png", 0, 0, 4, 4);
//Load nh t th mc Assets this.mGrassBackground = new RepeatingSpriteBackground(WIDTH, HEIGHT, this.mEngine.getTextureManager(), new AssetBitmapTextureAtlasSource(this, "ball.png"));
@Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger());
MyScene = new Scene(); MyScene.setBackground(this.mGrassBackground);//t i tng mGrassBackground lm cnh nn
//=====================LNG NGHE S KIN CHM VO MN HNH MyScene============================== //Bt s kin khi chm vo MyScene MyScene.setTouchAreaBindingEnabled(true);//cho php lng nghe MyScene.setOnSceneTouchListener(new IOnSceneTouchListener() { public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { System.out.println("Sprite onSceneTouchEvent: chm vo mn hnh"); System.out.println("Ta X = "+pSceneTouchEvent.getX()); System.out.println("Ta Y = "+pSceneTouchEvent.getY());
//Khi chm vo mn hnh ta di chuyn AnimatedSprite theo t y. animatedSprite.setPosition(animatedSprite.getX(), pSceneTouchEvent.getY()); return true; } }); //====================LNG NGHE S KIN KHI CHM VO ANIMATEDSPRITE============================ //t AnimatedSprite ti v tr x = 100,y = 100 this.animatedSprite = new AnimatedSprite(100, 100, this.tiledTextureRegion){ //Lng nghe s kin khi chm vo sprite @Override 33
Trng Thanh Anh Tun Email:tuanatt@nahi.vn public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){ System.out.println("AnimatedSprite onAreaTouched: chm vo animatedSprite"); System.out.println("Ta X = "+pTouchAreaLocalX); System.out.println("Ta Y = "+pTouchAreaLocalY); } return true; } }; animatedSprite.animate(100);//Sau 100milis ta s i bc nh MyScene.attachChild(animatedSprite);//Add vo MyScene MyScene.registerTouchArea(animatedSprite);//Phi ng k l cho php AnimatedSprite ny c lng nghe s kin //====================================================================================== //Cp nht (coi nh vng lp hot cnh) MyScene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() { // TODO Auto-generated method stub }
boolean chuyen = false; //Mun cp nht ci g th cho vo y @Override public void onUpdate(float pSecondsElapsed) { try { //Tm dng cp nht trong 10 ms Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Di chuyn sang phi if(!chuyen){ animatedSprite.setPosition(animatedSprite.getX()+5, animatedSprite.getY()); if(animatedSprite.getX() > 200)//Vt qu gii hn th cho di chuyn ngc li chuyen = true; }else{ animatedSprite.setPosition(animatedSprite.getX()-5, animatedSprite.getY()); if(animatedSprite.getX() < 10) 34
Trng Thanh Anh Tun Email:tuanatt@nahi.vn chuyen = false; } } });
return MyScene; } @Override public void onLoadComplete() {} } Source nh km AndEngine_Test07.rar
8.8 Xc nh va chm gia 2 sprite vi nhau : Thm 1 nh vo th mc asset : Pic 1: bg_image.png
Pic 3 : ball.png
on code chnh trong BaseGameActivity : public class MainActivity extends BaseGameActivity { //Khai bo thm 2 bin quan trng private Camera MyCamera;//Bin ny thng cu hnh mn hnh private Scene MyScene;//Qun l nhng g bn v.
private int WIDTH = 320;//Chiu rng vng hin th private int HEIGHT = 480;//Chiu cao vng hin th
35
Trng Thanh Anh Tun Email:tuanatt@nahi.vn private BitmapTextureAtlas bitmapTextureAtlas;//Lu nh trong b nh private TextureRegion textureRegion;//Lu khi load nh private Sprite sprite1,sprite2;//Sprite qu bng
private BitmapTextureAtlas bg_bitmapTextureAtlas;//Lu nh trong b nh private TextureRegion bg_textureRegion;//Lu khi load nh private Sprite bg_sprite;//Sprite to cnh nn
/** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }
@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; }
@Override public Engine onLoadEngine() { //Khi to vng hin th l 320*480 this.MyCamera = new Camera(0, 0, WIDTH, HEIGHT); //Yu cu mn hnh hin th nm ngang th ScreenOrientation.LANDSCAPE Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(WIDTH, HEIGHT), this.MyCamera)); return engine; }
@Override public void onLoadResources() { //Khai bo vng lu tr nh c kch thc 256,256. y l ci kh nht . S gii thch sau. this.bitmapTextureAtlas = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); //Load nh this.textureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.bitmapTextureAtlas, this, "ball.png", 0, 0); mEngine.getTextureManager().loadTextures(this.bitmapTextureAtlas); 36
@Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger());
MyScene = new Scene(); this.bg_sprite = new Sprite(0, 0, this.bg_textureRegion); MyScene.setBackground(new SpriteBackground(this.bg_sprite));
//t sprite1 ti v tr x = 0,y = 100 this.sprite1 = new Sprite(0, 100, this.textureRegion); MyScene.attachChild(sprite1);//Add vo MyScene
//t sprite2 ti v tr x = 300,y = 100 this.sprite2 = new Sprite(300, 100, this.textureRegion); MyScene.attachChild(sprite2);//Add vo MyScene
//Cp nht (coi nh vng lp hot cnh) MyScene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() { // TODO Auto-generated method stub }
//Mun cp nht ci g th cho vo y @Override public void onUpdate(float pSecondsElapsed) { //Qu bng u tin l chy t phi qua tri MainActivity.this.sprite1.setPosition(MainActivity.this.sprite1.getX()+1, MainActivity.this.sprite1.getY());
//Qu bng th 2 s chy c li t tri qua phi MainActivity.this.sprite2.setPosition(MainActivity.this.sprite2.getX()-1, MainActivity.this.sprite2.getY());
37
Trng Thanh Anh Tun Email:tuanatt@nahi.vn //Nu 2 qung bng ny va chm vo nhau ta cho n quay li v tr khi to if(MainActivity.this.sprite1.collidesWith(MainActivity.this.sprite2)){ MainActivity.this.sprite1.setPosition(0, MainActivity.this.sprite1.getY()); MainActivity.this.sprite2.setPosition(300, MainActivity.this.sprite2.getY()); } } }); return MyScene; } @Override public void onLoadComplete() {} } 8.9 To controler tng tc vi sprite : Thm 1 nh vo th mc asset : Pic 1 : ControlBase.png
Pic 2 : ControlKnob.png
Pic 3 : ball.png
Pic 4 : bg_image.png 38
Trng Thanh Anh Tun Email:tuanatt@nahi.vn
on code chnh trong BaseGameActivity : public class MainActivity extends BaseGameActivity { //Khai bo thm 2 bin quan trng private Camera MyCamera;//Bin ny thng cu hnh mn hnh private Scene MyScene;//Qun l nhng g bn v.
private int WIDTH = 480;//Chiu rng vng hin th private int HEIGHT = 320;//Chiu cao vng hin th
private BitmapTextureAtlas bitmapTextureAtlas;//Lu nh trong b nh private TextureRegion textureRegion;//Lu khi load nh private Sprite sprite;//Sprite qu bng
private BitmapTextureAtlas bg_bitmapTextureAtlas;//Lu nh trong b nh private TextureRegion bg_textureRegion;//Lu khi load nh private Sprite bg_sprite;//Sprite to cnh nn
//Khai bo cc bin dng cho vng iu khin private DigitalOnScreenControl mDigitalOnScreenControl; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion;
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } 39
Trng Thanh Anh Tun Email:tuanatt@nahi.vn
@Override public Engine onLoadEngine() { //Khi to vng hin th l 320*480 this.MyCamera = new Camera(0, 0, WIDTH, HEIGHT); //Yu cu mn hnh hin th nm ngang th ScreenOrientation.LANDSCAPE Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(WIDTH, HEIGHT), this.MyCamera)); return engine; }
@Override public void onLoadResources() { //Khai bo vng lu tr nh c kch thc 256,256. y l ci kh nht . S gii thch sau. this.bitmapTextureAtlas = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); //Load nh this.textureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.bitmapTextureAtlas, this, "ball.png", 0, 0); mEngine.getTextureManager().loadTextures(this.bitmapTextureAtlas);
@Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger());
MyScene = new Scene(); this.bg_sprite = new Sprite(0, 0, this.bg_textureRegion); 40
Trng Thanh Anh Tun Email:tuanatt@nahi.vn MyScene.setBackground(new SpriteBackground(this.bg_sprite));
//t sprite1 ti v tr x = 100,y = 100 this.sprite = new Sprite(100, 100, this.textureRegion); MyScene.attachChild(sprite);//Add vo MyScene
//=======================================IM QUAN TRNG NHT================ //Khai bo v s l iu kin khi ta chm vo vng iu khin mDigitalOnScreenControl = new DigitalOnScreenControl(0, HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.MyCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IOnScreenControlListener() { public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { // vng iu khin thay i ta s cho sprite di chuyn theo hng ta iu khin MainActivity.this.sprite.setPosition(MainActivity.this.sprite.getX() + pValueX, MainActivity.this.sprite.getY() + pValueY); } }); mDigitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); mDigitalOnScreenControl.getControlBase().setAlpha(0.7f); mDigitalOnScreenControl.getControlBase().setScaleCenter(0, 128); mDigitalOnScreenControl.getControlBase().setScale(0.8f); mDigitalOnScreenControl.getControlKnob().setScale(0.8f); mDigitalOnScreenControl.refreshControlKnobPosition();