191 comments on “JimVaders My Own Invaders Clone Thingie [Tutorial]

  1. Started with AndEngine last week and your tutorials are superb. Helped me with managing Bullets/Enemies and picked up some tips along the way. Great job!

  2. Just wanted to say thanks again for taking the time out to do this Jim, I really appreciate it.

  3. I have an issue with your singleton declarations, Ship,SensorListener classes.
    If you quit the game and run it again it throws exceptions ?

    • Well spotted !
      Apparently when you quit the game it doesn’t remove those static objects [memory leak .. I always forget that Java got memory leakage too >_<]
      just add this line before attaching the ship inside GameScene
      ship.sprite.detachSelf();

      I'll update the tutorial with those info

  4. Hi,
    Thanks for the great tutorial,
    I tried downloading the full project but the link doesn’t seem to be working. Any chance you can upload it again?

    Thanks

      • Your right, I’ve been able to download it now.
        I have no idea why it wasn’t working before (mediafire gave me a page telling me the file didn’t exist)!

  5. Hi,

    you made a good job I see

    I tried to do like you but i don’t succes

    I did all like you (Android 4.0, ADT 18.0, Eclipse Git addon, GLES2.0) but it still not working..!
    I tried to take your all project and compile it but there always have errors and even if i tried to resolve then, i can’t make an .apk (“Conversion to Dalvik format failed with error 1”)… :-/

    I really hope you can help me.

    Thank !

    Sénastien

  6. Yes I already read it and do it… so many times… maybe I’m too beginner but it looks like easy !
    Seriously I really would like your help, I think it will not take much time.

    Thank for your answer,

    Sébastien

    • you plug in your device (phone/tablet) to your computer , make sure the drivers are installed properly and run [make sure you are building to an SDK that’s less than your phone’s android version]
      the game should run on your device directly

  7. Actually you can run it on the Android Emulator with the latest version of the AVD. You just need to set enable GPU and it can run GLES2 AndEngine no problem!

      • Thanks. Yep if you edit one of your existing virtual devices in AVD Manager or create a new one, under Hardware section you can click New -> select GPU emulation as property -> set Value to yes. This will allow GLES2 to run on the emulator; however, I believe that you need to disable Snapshot for this to work.

  8. Very nice tutorial! Thank you, helped me a lot!

    (Note: you have a few messed up if conditions:

    in part about moving ‘ship’ using accelerometer

    if (newX newX = sprite.getX() + accelerometerSpeedX;
    else
    newX = rL;

    and in where you explain cleaner in GameScene

    if (b.sprite.getY() BulletPool.sharedBulletPool().recyclePoolItem(b);
    it.remove();
    continue;
    }
    )

    • Thanks for pointing that out but in my defense I didn’t mess this up
      it’s wordpress’ fault .. every now and then it decided to parse some parts of the code as HTML instead of text >_>

  9. Just downloaded the whole tutorial why do you use import.org.anddev rather that import.org.andengine?

    • I don’t .. the code I have got import org.andengine [which class did you see that in ?]
      and btw , I don’t add imports manually , eclipse manages that for me

    • oh craps !
      I put the wrong code on github >.< That's the version I first created for GLES1
      delete your old fork and fork again , sorry about that

  10. Hi… great tutorial)

    How to do that – when i’m in a GameScene, and when i press back button on mobile – app close, but i want to get back in the meny, and then if i in meny, i press back button – the app will close?

    sorry for my english, i’m from russia!

    • basically , in your onBackPressed method override inside the BaseActivity you’ll have to check which scene is your current and do what you want .. for example
      if(mCurrentScene instanceof GameScene){
      //..unload the GameScene attributes and clean it up then change the current scene to main menu
      }

      • if you are new to programming I suggest you work on that before getting into game programming
        you should check the logCat and see what the error is and try to solve it .. sorry but I don’t provide personal tuition

  11. So, I tried running different examples on AndEngine and I connected my own phone since it doesn’t run on an emulator. When I try to run it this error occurs “Android library projects cannot be launched”. But I successfully ran your tutorial. Great tutorial btw. 😀

  12. this is wrong , cos activity.setCurrentScene takes other parameter type then MainMenuScene returns
    DelayModifier dMod = new DelayModifier(2, new IEntityModifierListener() {
    @Override
    public void onModifierStarted(IModifier arg0, IEntity arg1) {
    }
    public void onModifierFinished(IModifier arg0, IEntity arg1) {
    activity.setCurrentScene(new MainMenuScene());
    }
    });
    registerEntityModifier(dMod);

    • it’s not wrong , setCurrentScene takes a Scene object , MainMenuScene extends MenuScene which extends Scene , so it should work

      • I try to run the tutorial, but when i type exactly the koskow code has posted, I have errors because not receive the second parameter, and eclipse try to resolv this deleting new IEntityModifierListener(){});

        Can you helpme with this error, really can’t explain what is the reason of that error :S

      • I updated the post with another way of doing it , I’m not sure why this won’t work but the other method should work
        go check it out 😀

    • so far I haven’t done any specific tutorials , all of mine are complete games [or something you’d call a game :P]
      I’m currently busy working on lots of random stuff and doing other life stuff 😛
      but maybe someday .. you never know 😀

      • Haha. Just sayin though because we’re doing a mouse joint based right now for our capstone project. And we’re having a hard time figuring it out how to use mouse joint. But yeah keep up the good work. 😀

  13. Hey Jimmar,
    im in the beginning and copied the code word for word but the splash doesnt turn to the main. so i cant get past that part. its supposed to take 2 seconds right. i test it and just sit here and it never takes it to the blue screen where it says start.

    • Maybe you didn’t register the entity modifier after you created it [the one that waits for 2 seconds]
      you can also go to the github link [at the bottom of the post] and view my code for those certain classes , maybe you missed a part or something [sometimes wordpress messes up my code too .. so it could be wordpress’ fault]

  14. Hello JiMMaR, thanks for your tutorials, they are really great 🙂

    I have a question concerning the splash screen. I don’t understand how to load textures for the game. Could you provide an exemple? (in loadResources() of SplashScene)

    If, for exemple, I want to have a sprite for my ship, how should I load it in SplashScene, and use it in my GameScene?

    Thanks again for everything,
    trifus

      • Thanks for the quicke reply!

        I’m not having a problem with the load of textures itself. I read your other tutorial (with the ninja) 🙂

        My problem is to load a texture in SplashScene, and use it in another file (GameScene)
        I must declare the ITexture and ITextureRegion in SplashScene, in loadResources(), I get it, but how use them in GameScene?

        In the exemple you gave me:
        final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion, this.getVertexBufferObjectManager());

        Instead of this.mFaceTextureRegion, since it is not declared there, must I write SplashScene.mFaceTextureRegion? It must be static then?

        My question seems odd, but I can’t figure the proper way to do it, I don’t know why 😀

      • for this you have 2 approaches
        1 – have those objects declared as static variables , so you can access them as SplashScene.mFaceTextureRegion. [not recommended for big games]

        2 – create a SINGLETON class to manage resources [i.e ResourceManager] and have all your texture variables in there, then set setters and getters to get them [or just make them public and access them directly] .. whichever you prefer

        just make sure that your ResourceManager is a singleton, and you don’t create more than one instance of it !

        and your question is not odd , it’s a game design problem 😀

      • Thanks! Perfect answer 🙂 That was I thought.

        So my idea with the static variables was valid, but not the best one 😀

        I will try a singleton class then.

        Thank you for this quick and useful answer!
        trifus

  15. JiMMar great tutoral, but i would like to ask and say sth. You said that:
    ” have those objects declared as static variables , so you can access them as SplashScene.mFaceTextureRegion. [not recommended for big games]” well im not sure for that.

    I red http://developer.android.com/guide/practices/performance.html#internal_get_set
    and using static fields is recomended for that. Of course 2nd option (singleton) is usless as well. But i think in big projects is better using static fields to get sth.

    and one more time thanks for great tut:)
    regards Toby

    • That link was talking about the setters and getters and suggested that you should access the data directly when inside the class
      and the next topic suggests that you use final static whenever possible over just static.
      and that’s not recommended for big games cause you may have issues remembering where you saved your texture object , and if the main object class is not a singleton , there is a chance that you create another instance of it which means that this new instance won’t have the same objects in the first one which means the data you initialized won’t be usable from this new instance.
      This is a matter of taste and habit too .. I’m currently going with the ResourceManager method, here’s an example of my class
      http://pastebin.com/h1NiLNZM

  16. hey jim fantastic job …(though i hav nt tried it yet….but atleast u gave a meaningful text which i can undrstnd….) !!!
    wht abt a video tut abt it….it makes life more easy !!!
    thnks bdw !!!
    great one !!

    • I’m not a fan of video tutorials 😛 [specially for mere text programming that doesn’t include tricky UI]
      I think you can find couple of video tutorials about AndEngine on youtube though

  17. as u say sire….but i wish and hope u will continue to more complex tuts abt andengine….
    (well i am tryng this thing now….lets c how it shapes out)

  18. sem = new SequenceEntityModifier(pem, am2) {

    @Override
    public void onModifierFinished(IModifier pModifier,
    IEntity pItem) {
    // TODO Auto-generated method stub
    super.onModifierFinished(pModifier, pItem);
    “AAAA”
    }

    };
    mSpAttack.clearEntityModifiers();
    mSpAttack.registerEntityModifier(sem);

    =>> “AAAA” is worked but mSpAttack trigger only one times

    sem = new SequenceEntityModifier(pem, am2) {

    @Override
    public void onModifierFinished(IModifier pModifier,
    IEntity pItem) {
    // TODO Auto-generated method stub
    super.onModifierFinished(pModifier, pItem);
    “AAAA”
    }

    };
    mSpAttack.clearEntityModifiers();
    mSpAttack.registerEntityModifier(sem.deepCopy());

    =>> “AAAA” is not worked but mSpAttack trigger more times

  19. Shouldn’t LoadResources() in the SplashScene class look more like this:

    private void LoadResources(){

    //TODO: this will be used to load

    //images, music etc…

    DelayModifier dMod = new DelayModifier(2);

    dMod.addModifierListener(new IModifierListener(){

    @Override

    public void onModifierStarted(IModifier arg0, IEntity arg1){

    }

    @Override

    public void onModifierFinished(IModifier arg0, IEntity arg1){

    activity.setCurrentScene(new MainMenuScene());

    }

    });

    registerEntityModifier(dMod);

    }

    • LOVE the Tutorial BTW. I’m not trying to be a code troll, I was just having an issue implementing the method. 🙂

      • nobody considered you as a code troll 😛
        and in AndEngine there are Modifiers and EntityModifiers, your method is correct but mine is correct too
        there are lots of things with no right answer , both are correct 😀

  20. Hello JiMMaR!

    i have read this tutorial and was a great help for me, tried your approach of using scenes in a different class then extending it to scene class.

    however, when adding sprites, activity(which is BaseActivity.getSharedInstanced).getTextureManager() results to a null pointer exceptions, is there a workaround for this. TIA.

  21. Hi, thanks for this tutorial, It’s help me so much. I think that you need to make more tutorials like this, or expanding this example with tutorials about how to manage assets and more, would be very useful 😀

    • you can set certain resolution [for example width = 800 , height = 480] and the game will be scaled up/down to match the device’s actual resolution
      or you can work with equations on all positions and have couple of assets ready for it [lots of work, but better quality]

  22. sir Thank you for your great tutorial ..
    very nice

    sir can i request for make a tutorial for texturepacker for sprite
    thank you sir more power 🙂

  23. Hi, mate.
    I’m newbie, and I just learned this Andengine.
    It’s awesome and I was interested to this tutorial, but It make me a little confused cause of just piece of code that I can read, not all project.
    I got error, espessially when I create Create a new class called MainMenuScene that extends MenuScene and implements IOnMenuItemClickListener.
    May I know whole of this source code?
    At least Java on src folder project.
    Thanks so much 🙂

    • that means that your class will be like
      class MainMenuScene extends MenuScene implements iOnMenuItemClickListener{

      }
      the whole source code is available at the last section of the tutorial, I provided a mediafire link and a github link
      you can download from both , and can also view the code on github

  24. Question in this part for EnemyPool

    @Override

    protected void onHandleObtainItem(Enemy pItem) {

    pItem.init();

    }

    Why did you need to call init()? why not just return an enemy object immediately since init() would be called in constructor Enemy() anyway?

    @Override
    protected Object onAllocatePoolItem() {
    // TODO Auto-generated method stub
    return new Enemy();
    }

    in Enemy(), init() is called.

    • That’s the point of using a pool , when you are returning an item to the pool it stays there till you call it again , with it’s same properties
      when you call it back , onHandleObtainItem is called so we init it [constructor is not called again , this is a reused object]
      when there are no items in the pool, onAllocatePoolItem gets called which creates a new object [and constructor gets called]

      hope that cleared it 😀

      • oh didn’t realize it till now that the call back was onhandle and not onallocate. i get it now. thanks for the clarification! 😀

  25. Hi Jim! Just one more question. Again about the pool. the method obtainPoolItem() calls both onHandleObtainItem and onAllocatePoolItem? The difference is just that onAllocatePoolItem is called if there is no item in the pool. And if there is an available item to be reused, onHandleObtainItem is called.Did i get that right? Just wanna ask why the bullet pool didn’t have onHandleObtainItem if it’s job is to reuse recycled items in the pool. Since Bulletpool only has onAllocatePoolItem, does that mean that it creates new Bullet items everytime shoot() is called? Thanks.

    • Notice that those methods are overriden , so they get called even if you didn’t write them [part of the GenericPool class]
      the only reason BulletPool didn’t have onHandleObtainItem is because I’m initializing it in shoot() instead of doing that in the pool class
      I’m kind of showing examples of how pools can be used in 2 places with 2 different cases and how you can initialize the object in the pool instead of doing that after obtaining it

      • Oh right since BulletPool is a sub class of Generic Pool. I totally get it now. Thank you very much for the effort of explaining. You really explain things in a way that could easily be understood. 😀 This will really help me out a lot!:D

  26. Hello JiMMaR I really aprecciate your tutorials and your help. Sorry for my english.I hope you understand 🙂 I follow all the steps like you explain but i got error when i run the proyect on android emulador couldnt start ,I select Gpu emulation as property but i get the same error,but this doesnt happend whit gles1… I try running on my smarthphone(ISC android 4.0.3 ) ,i can see the icon of android proyect but suddenly stop

  27. Firstly thanks for your great tutorial. This tutorial is awesome and helpful for me. I tried to used sprite instead of rectangle object and include explosion sound to Enemy class. It’s work well but doesn’t show ResultScene :(. ResultScene normally shown if not using sprite. My Enemy class look like below:

    private BaseActivity activity;

    public BitmapTextureAtlas mBitmapTextureAtlas;
    public TextureRegion mTextureRegion;

    public Sprite sprite;

    public int hp;
    protected final int MAX_HEALTH = 2;

    public Enemy() {
    activity = BaseActivity .getSharedInstance();
    BitmapTextureAtlasTextureRegionFactory.setAssetBasePath(“gfx/”);
    mBitmapTextureAtlas = new BitmapTextureAtlas(
    activity.getTextureManager(), 128, 256, TextureOptions.BILINEAR);
    mTextureRegion = BitmapTextureAtlasTextureRegionFactory
    .createFromAsset(mBitmapTextureAtlas, activity, “bee.png”, 0, 0);
    mBitmapTextureAtlas.load();
    sprite = new Sprite(0, 0, mTextureRegion,
    activity.getVertexBufferObjectManager());
    init();
    }

    I guess my activity always load mBitmapTextureAtlas and EnemyLayer never empty right?
    Do you have any idea?

    Thank in advance.

    • you can check how many children and entity has [in this case EnemyLayer] by using EnemyLayer.getChildCount(), try printing that value to the log [using Debug.d()] every time an enemy is killed to check if that’s the problem or not
      as for the way you are doing it , since you are using the same texture for all sprites , it’s better to load one texture region and use the same one for all sprites .. it’s better for the memory

      • Thank you Jim!

        I have one more question:
        firstly my MainMenuScene extends MenuScene
        secondly in constructor MainMenuScene(), I have been created 3 ITextureRegions by 1 BitmapTextureAtlas then add them into addMenuItem();
        unfortunately It’s only show the last ITextureRegion for all MenuItems. Why?
        I tried to create 3 BitmapTextureAtlas corresponds it will display exactly what I want. yeah I know the second way it’s worked with bad performance. I wanna save my memory. What’s happened with MenuScene? This is a bug or I have something not right? my codes looks like bellow:

        public MainMenuScene() {

        BitmapTextureAtlasTextureRegionFactory.setAssetBasePath(“gfx/”);

        this.mBitmapTextureAtlas = new BitmapTextureAtlas(
        this.getTextureManager(), 256, 128, TextureOptions.BILINEAR);
        this.mButton1ITextureRegion = BitmapTextureAtlasTextureRegionFactory
        .createFromAsset(this.mBitmapTextureAtlas, mActivity,
        “button1.png”, 0, 0);
        this.mButton2ITextureRegion = BitmapTextureAtlasTextureRegionFactory
        .createFromAsset(this.mBitmapTextureAtlas, mActivity,
        “button2.png”, 0, 0);
        this.mButton3ITextureRegion = BitmapTextureAtlasTextureRegionFactory
        .createFromAsset(this.mBitmapTextureAtlas, mActivity,
        “button3.png”, 0, 0);
        this.mBitmapTextureAtlas.load();

        IMenuItem button1= new SpriteMenuItem(0,
        this.mButton1ITextureRegion ,
        mActivity.getVertexBufferObjectManager());
        IMenuItem button2= new SpriteMenuItem(1,
        this.mButton3ITextureRegion ,
        mActivity.getVertexBufferObjectManager());
        IMenuItem button3= new SpriteMenuItem(2,
        this.mButton3ITextureRegion ,
        mActivity.getVertexBufferObjectManager());
        button1.setposition(x,y);
        button2.setposition(x,y + 10);
        button3.setposition(x,y + 30);
        addMenuItem(button1);
        addMenuItem(button2);
        addMenuItem(button3);
        }

      • Imagine the textureAtlas as a wall where you put posters on
        you are putting your first poster [button1.png] on the top left corner [0,0]
        then you put your 2nd poster [button2.png] on the top left corner too [0,0]
        then you put your 3rd poster [button3.png] on the top left corner too [0,0]
        so you are putting your posters above each others, you’ll only see the last one

        create a texture atlas that can handle all 3 images [size wise] and then make sure you place them correctly so that there would be a padding between the sprites [2 pixels padding are enough]

      • Thank you Jim 🙂 I was succeed. Now I really know how BitMapTextureAtlas work!!!
        I think if include javadocs Andengine becoming better.

  28. Thanks bro for your works,I am on the way of learning your fabulous tutorial.
    In Your ResourceManager Class Inside LoadMainMenu() I didn’t understand CONST.WIDTH, & CONST.HEIGHT? can u give us explanation? Is it the device width & height?

    BuildableBitmapTextureAtlas texture = new BuildableBitmapTextureAtlas(
    mEngine.getTextureManager(), CONST.WIDTH, CONST.HEIGHT);

    • it took me a while to figure out what you were talking about 😛
      well .. I just put those values here as a starter , so it doesn’t matter .. testureAtlas is like a big board where you stick your sprites on it .. so you have to make it big enough for all of your sprites to fit but don’t use one that’s larger than 2048 x 2048 cause it won’t work on most devices
      just put any value that you see fit for the sprites you have , you can always try or just go with the maximum at first then optimize later on [or calculate yourself]

  29. Thanks for quick reply. I understand why BuildableBitmapTextureAtlas stands for.

    what does this line do?

    texture.build(new BlackPawnTextureAtlasBuilder(
    0, 1, 4));

  30. Hi great tutorial, I am having for some reason a problem with R.string.start on the public MainMenuScene its marking “start” and says “start cannot be resolved or is not a field” could you help me may be I forgot to add some thing

  31. Great JOb
    I found this very interesting. Please I will be most grateful if you send the updated copy of the code to me through this address [email removed]

    • there is no updated copy , you can get the latest version from the github link that I provided, there is a download link inside so it shouldn’t be very hard to do

  32. I have a custom scene called GameScene. I create a method LoadResources() inside it.It works fine.

    public class GameScene extends Scene{

    BaseActivity activity;
    // Below two class is responsible for creating button,both extends TileSprite class
    public RedButtonBean aRedButtonBean;
    public BlueButtonBean aBlueButtonBean;

    public GameScene() {
    //inside constructor i call it

    LoadResources();
    aRedButtonBean = new RedButtonBean(0, 200, iRedTiledTextureRegion,
    activity.getVertexBufferObjectManager(), instance);
    attachChild(aRedButtonBean);

    }

    public void LoadResources() {
    //inside this class
    BitmapTextureAtlasTextureRegionFactory.setAssetBasePath(“gfx/”);
    activity = BaseActivity.getSharedInstance();
    BuildableBitmapTextureAtlas texture = new BuildableBitmapTextureAtlas(
    activity.getTextureManager(), 2048, 2048);
    this.iRedTiledTextureRegion = BitmapTextureAtlasTextureRegionFactory
    .createTiledFromAsset(texture, activity,
    “button_tiled_red.png”, 2, 1);
    this.iBlueTiledTextureRegion = BitmapTextureAtlasTextureRegionFactory
    .createTiledFromAsset(texture, activity,
    “button_tiled_blue.png”, 2, 1);

    try {
    texture.build(new BlackPawnTextureAtlasBuilder(
    0, 1, 4));
    texture.load();
    } catch (TextureAtlasBuilderException e) {

    e.printStackTrace();
    }
    }
    }

    }
    Problem: When i put my LoadResources() method inside ResourceManager,i can’t call it. when i write like in GameScene Constructor
    ResourceManager aResourceManager;
    public GameScene() {

    aResourceManager=ResourceManager.getInstance();
    LoadResources(activity);

    }
    i got error. Null pointer exception. Can u help me how to use ResourceManager in My GameScene class?

    • are you sure that your ResourceManager class’s instance is decalred like this ?
      private static final ResourceManager INSTANCE = new ResourceManager();
      if you are not doing that then your INSTANCE is null by default

      also please use pastebin to put code , don’t put long codes in the comments

  33. Problem:

    I am trying to replace the sprite in ship class from rectangle to an animated sprite.. i have tested the animated sprite , its texture and its TiledTextureRegion in a seperate project and it works fine. But when i add this to the sprite in ship the game crashes with null pointer exception. Logcat reports the following:

    java.lang.NullPointerException
    at com.example.jimvaders.Ship.(Ship.java:33)
    at com.example.jimvaders.Ship.getSharedInstance(Ship.java:27)
    at com.example.jimvaders.GameScene.(GameScene.java:33)

    The Texture and TiledTextureRegion are populated in onCreateResources() of BaseActivity.java.

    the code for sprite constructor regarding the animatedSprite creation is :

    sprite = new AnimatedSprite(0,0, BaseActivity.getSharedInstance().myTextureRegion,
    BaseActivity.getSharedInstance().getVertexBufferObjectManager());
    where myTextureRegion is a TiledTextureRegion from BaseActivity.

    Any ideas how to use animated sprite in ship.java?

    • I tried using Sprite instead of AnimatedSprite and it works.. used the same spritesheet (with tiles) for the texture region of that sprite and it works.. why is animated sprite not working? please help!

      • switching between Sprite and AnimatedSprite should work .. it’s weird that it’s not working
        can you send me your whole project via email ? [my email address is in the about page]
        also include the full stackTrace of the Logcat in the email

      • Thanks for the reply JiMMaR, i got that working. Just one more question my enemy class uses a Sprite sprite; instead of rectangle. The texture regions are placed on a bitmapTextureAtlas inside OnCreateResources() of BaseActivity. I have tested them and they are working perfectly (given their manual positioning on atlas no problems there). So in constructor of Enemy.java i tried

        sprite = new Sprite(0,0,activity.myTextureRegion.deepCopy(),activity.getVertexbuffer…..;

        at this point the logcat gives the error onCreateScene failed.

        Please if you don’t understand the problem above just give a hint on “how to access the texture regions created in onCreateResources() method of the baseActivity from another class such as Enemy.java in this tutorial?”

      • no need for deepCopy() [actually it was replaced by clone() if I remember correctly .. but you probably won’t need both of them anyway]
        what you are doing should work fine, maybe if you gave me the exact error in logcat I could figure out what’s the problem exactly

  34. Having a problem with the tilt movement, the square just stays there it doesn’t move if I tilt the device any help?

  35. Any advice or tutorials you know of to implement physics box 2d in an object riented style like the one you taught? I am pretty proficient at AndEngine but am struggling to make a solid smotth transition into making my programs Oobject oriented.

    • I don’t think I can really help you in that .. also my code is not really that optimal in object oriented way , I learned lots of more stuff [and a lot more to go] about organizing classes [software engineering the code] and I did make some bad moves in my tutorials but it’s a good start
      one of my friends had a rule that each class shouldn’t exceed about 350 line, that’s not really a strict rule but it can get you thinking in ways of how to try and optimize your work and restructure it
      also try to always think about improvements , write your code in a way that if you need to add new features [new enemies].. it’ll be pretty easy [and the best would be if you didn’t need to change much from the existing code, have the classes work generally]
      of course this would cause you trouble at first, some people argue that for small projects it’s not worth the time .. that could be true, but if you are just starting I think it’s good to learn how to do stuff the proper way, after all if you couldn’t do the small thing how are you gonna do the bigger ones ?

      • Thanks for the reply man I really appreciate you taking the time to respond. It has been tough getting started with andEngine even though I am a pretty proficient coder. I have ome along really well though. I have put about 3 days into it and cant believe how far I have come. Your tutorial has helped a ton. I still cant make graphics to save my life but other then that lol

    • You can load whatever you want in the a TextureAtlas, they are not connected to having different scenes
      if you are using small sprites , you might load all of your textures in one TextureAtlas and at once

  36. I’m trying out your method of calling a class that extends Scene in my project but I am encountering an error. When I try to call the scene(well, class extends scene), I am getting a NullPointerException error.

    This is how I’m calling the class
    public void createGameScenes() {
    //Create Game Scene
    titleScene = new Game(engine, camera);
    }

    This is how I set current scene(error happens before I even get here)
    public void setCurrentScene(SceneType scene) {
    currentScene = scene;
    switch (scene){
    case SPLASH:
    break;
    case TITLE:
    engine.setScene(titleScene);
    break;
    }
    }

    This is the class I’m calling
    public class Game extends Scene{
    // variable were here…

    public Game(Engine engine, final SmoothCamera mCamera){
    //code of game here…
    }
    }

    Few more functions for game follow ()

    What could be the reason I am getting a NullPointerException error?

    • forgot to mention, in the logcat. It says this:
      12-19 11:54:22.212: E/AndroidRuntime(5934): java.lang.NullPointerException
      12-19 11:54:22.212: E/AndroidRuntime(5934): at com.templateandroid.Game.(Game.java:111)

      however, I have checked my code and I am sure that it shouldn’t be null…

      • My problem was slowly solved through studying the code a bit and a lot of help from the andengine forums XD Thanks again for the tutorial though, helped me start up on transitioning between scenes

      • The issue was in relation with the singleton thing. However in my case, I wanted to do it with passing BitmapTextureAtlas’es through classes. Didn’t think I had to singleton the entire class itself. Actually gonna try to implement that in my code now, but if ever that was the problem.

  37. Great tutorial! I finished all and it worked with some minor changes.
    I have a question thou. I hope you can answer…

    If i want more enemies with different capabilities like other color, more life, bullets, different move pattern etc
    How do i have to change the EnemyPool and the EnemyLayer?

    Or do i have to make new pools and layers for each new enemy?

    I tried to look up stuff about object pooling but those examples where about business applications not games. Well thank anyways!

    • here’s a quick solution to you so you don’t have to change much of the code
      – create an interface class [call it iEnemy for example or something] and make it have all the necessary enemy methods
      – create 2 classes [or more , depending on the number of enemies you have] I’ll go with EnemyRed and EnemyBlue , both should implement iEnemy [public class EnemyRed implements iEnemy] and you will probably have to create a Class called Enemy and make them [EnemyRed and EnemyBlue] extend this Enemy class
      – have your EnemyPool be of type iEnemy [now this pool can take both EnemyRed and EnemyBlue]

      you should have different functionalists included inside the EnemyRed/Blue classes , like how they attack and stuff .. for example you can have red shoot bullets while blue doesn’t
      if you did that for example , you either have the enemies shoot something onUpdate inside the class , or implement a function shoot that gets called from somewhere else and have it empty inside blue
      there are lots of ways .. but I just pointed out some

      I hope that made sense 😛

  38. Muchas gracias.
    Es un gran tutorial XD
    Espero hacer mi juego pronto XD

    Thank you very much.
    It’s a great tutorial XD
    I hope soon make my game XD

  39. Sit, you did it great, but I should tell you that this tutorial isnt for beginners 🙂 There’s a lot of implicit thing(such as calls that you don’t cite). But I think this is a great tutorial! You must translate it to other languages so more peoples can gain access to it!

    • Thank you for reading !!
      There are some parts of the code that I didn’t include and just explained or said that you have to do [which is usually explained previously]
      could you point out which part exactly makes you feel that this is not for beginners or if I didn’t explain something ? this is for beginners in AndEngine but not exactly for beginners in Java though

  40. Hey I just wanted to say thank you for posting this tutorial. Guys like you are the ones that really make a difference in the world. When the time is right I hope to do the same.

    Oh I’m also gonna buy your book.

    • I’m glad that I had an impact on someone 😀
      it’s not exactly my book, but I assure you it’s pretty good .. thanks for passing by ^^

  41. Quick question regarding this tutorial, I got the the part were you “Kill the squares” however after implementing it, when I shoot the boxes, they die but they don’t disappear. I know they die because i put a log message to output “collide!” when they are hit and if i position my ship to the edge and keep shooting, the “collide!” only outputs 4 times, which means 2 squares were killed and they don’t exist anymore, except they visually do.
    Also in the tutorial, just after you introduce the purge() method, there are blocks of code(used to create the enemies and animate them into the game) under it that didn’t specify where they should be put. I ended up putting that code in the constructor.
    I’m not sure if you have addressed any of these in the comments, to if you have let me know and I will go through the comments.
    Side note: still waiting for the book you took part in too arrive tomorrow. Using this tutorial as a warm-up.

    • I think the problem may be that detach isn’t called after the square dies. Also I don’t think purgeAndRestart is ever called. I may be mistaken because I haven’t finished the tutorial yet.

      • Actually I have finished the tutorial now and everything turned out fine. I like the way the tutorial was made, you get the sense of accomplishment when you’re done because not every single step is provided. Also it didn’t hold your hand too much along the way. If this is a beginners tutorial then I definitely need to step my game up because it felt a shy away from advanced Java. I’m going to play around with it while I wait for the book and truly get started. I would advice everyone who do this tutorial to finish it first before looking at the source if you want to learn something.

      • good catch about the code block, I guess adding that “annoying note” in the middle causes some confusion , I added more clarifications now 😛
        and yeah, the whole point of this tutorial is to be able to make a basic game, with setting small targets/goals so you feel accomplishments and that helps in driving you forward to continue [it’s long so I have to do that or the reader would get bored :P]
        it’s supposed to be kinda for beginners in AndEngine [not beginners in java .. even though I do explain some basic java stuff here and there], I’m not an expert in writing tutorials I just thought I’d write something in a way that I’d like them to be [or maybe I got influenced by other tutorials .. meh]

        anyway .. enough blabbering from me for now .. glad you enjoyed the tutorial 😀

    • I can’t help you without seeing what you did
      but first try and download the whole code and see if it’s the same or not .. you can paste your code on pastebin.com and put a link here so I view it after checking with the whole source code

  42. Thanks Jim for such an awesome tutorial.I downloaded the whole code and ran it.But the problem is the ship is not moving at all.Please help me.

  43. Hey jim can u teach how to make the enemy shoot against the player? I’m getting nuts trying do that, please can u help me? tks

  44. Hey, I was wondering if I wanted to add a counter to tell you how long it took you to complete the level, how would I do that. Currently I have a System.CurrentTImeMillis at the beginning, and another System.CurrentTImeMillis at the end of the level (when there are no more enemies) and I subtract them and divide by 1000 to get seconds. But I cannot get it to work, I always get the same answer. Where would I put the code to get the time at the end. If Im doing it right at all?

    • while I cannot really help you in your way without seeing a code , I’ll give you another solution [kinda]
      in a game that I made, I had to implement a timer to show the user how much time has elapsed and update it on the screen, to do that you use an IUpdateHandler [make a private class and have it implement IUpdateHandler] and override the onUpdate() method.
      onUpdate gives you the time elapsed in seconds, so get a float and keep on adding till the game ends
      you might want to look for more tutorials on using IUpdateHandler
      thanks for passing by

  45. DUDE , millions thanks for the “fablous” :] tutotrial
    I tried to implement it with latest version of andenegine {Anchor Center}
    I fixed all issues of the cordinates changes except this
    float finalPosX = (i % 6) * 4 * e.sprite.getWidth();
    float finalPosY = ((int) (i / 6)) * e.sprite.getHeight() * 2;
    i tried lots of things , but ukh nothing worked , the enemies overalping each others without space just like this
    ****
    ** *
    thanks again , your tutotrial helped me alot to start games development

    • starnge i replaced MoveModfier function with
      e.sprite.registerEntityModifier(new MoveXModifier(2, randPosX, finalPosX));
      e.sprite.registerEntityModifier(new MoveYModifier(2, randPosY, finalPosY));

      and now enemies appear correct — time to shot some nasty aliens xP

  46. I want to add music to the start of the GameScene with the code youve provided. I have my Music set up in the BaseActivity. But I just need to know where to put the music.start() and music.stop() so that the music will start at the beginning of the game and end when the ResultScene shows up, and the music will restart when the Game restarts after the GameScene. I have my music set up with MusicFactory. Thanks! 🙂

  47. Hi jimmar i make a game with help of yours, i have just a problem; i replace the rectangel(Enemy) for a sprite and make the same in Ship, when i tried to make a collision detection on class GameScene, in method cleaner(), if doesn´t detected the collision between ship.sprite and e.spriterojo so i called them. hier is some code….

    if (b.sprite.collidesWith(e.spriterojo)) {
    //e.spriterojo.setColor(Color.BLACK);
    //collisionDetection();
    if (!e.gotHit()) {
    createExplosion(e.spriterojo.getX(), e.spriterojo.getY(),
    e.spriterojo.getParent(),
    BaseActivity.getSharedInstance());
    EnemyPool.sharedEnemyPool().recyclePoolItem(e);
    eIt.remove();
    //mSound.play();
    }
    BulletPool.sharedBulletPool().recyclePoolItem(b);
    it.remove();
    break;
    }else if(ship.sprite.collidesWith(e.spriterojo)){
    resetValues();
    }
    }
    }

    how can i make collision between ship.sprite and e.spriterojo, thanks for any help

  48. Hi Sir,
    I am developing a live wallpaper based on Andengine GLES 2 Anchor centre branch with help of our Andengine development cook book .[ I am greatly thank full to all peoples behind the book its awsome!! ]. But I am suffering of texture loosing on low end device , I have posted the questions with all details and code in Andengine forum and Stack over flow , It will be very help full for me if I get any suggestions from you, Its my humble request for a look on the issue

    these are the links to my posts

    http://www.andengine.org/forums/live-wallpaper-extension/loosing-textures-on-low-end-devices-t12402.html

    http://stackoverflow.com/questions/17259444/andengine-live-wallpaper-loosing-textures-on-low-end-device

    hopefully

    Renjith KN

  49. everything works fine, but in catlog it keeps spamming error “recycled than obtained!”
    But, everything runs fine, I’m just curious why it says that error?

  50. everything works fine, but in logcat it keeps spamming error “More items recycled than obtained!”
    But, everything runs fine. I’m just curious why it says that error?

    • your screenshot doesn’t show much , I need to see the part of the logcat where it says what the problem is [did you make sure the engine works fine ? using the installing GLES2.0 tutorial ?]
      I’m also interested in your attack on titans game 😛

  51. That is another graet Tutorial..thanks alot and please keep sharing your tutorials..again Thanks Alot and much appreciated..!!

  52. Hi jimmar i make a game with help of yours, i have just a problem; i replace the rectangel(Enemy) for a sprite and make the same in Ship, when i tried to make a collision detection on class GameScene, in method cleaner(), if doesn´t detected the collision between ship.sprite and e.spriterojo so i called them. hier is some code….

    if (b.sprite.collidesWith(e.spriterojo)) {
    //e.spriterojo.setColor(Color.BLACK);
    //collisionDetection();
    if (!e.gotHit()) {
    createExplosion(e.spriterojo.getX(), e.spriterojo.getY(),
    e.spriterojo.getParent(),
    BaseActivity.getSharedInstance());
    EnemyPool.sharedEnemyPool().recyclePoolItem(e);
    eIt.remove();
    //mSound.play();
    }
    BulletPool.sharedBulletPool().recyclePoolItem(b);
    it.remove();
    break;
    }else if(ship.sprite.collidesWith(e.spriterojo)){
    resetValues();
    }
    }
    }

    how can i make collision between ship.sprite and e.spriterojo, thanks for any help

  53. Hi jimmar
    Awesome tutorial, i’m working on a similar project like this too. It helped me alots 😀
    I have 2 question about this tutorial
    1) Rectangle rect = new Rectangle(posX, posY, 10, 10, activity.getVertexBufferObjectManager());
    I wonder if a particle system can hold more than 1 texture?, so it can emit particle with random texture? Or we have to create multi particle system? Also, you said that we can use Sprite instead of Rectangle? Can you show me the code use to create it? I’m using Gles2 anchor center branch

    2) I’m working on the HP’s bar of character, Can i, somehow, implement the sprite’s drawMethod, to make it draw on every update?

    Thanks

    • good job man, I like it !
      but if you are looking for a market point of view , people don’t care if your game uses images or not, they don’t care what kind of handicaps you put to yourself while making the game
      they care that it’d be fun to play , and it’d look good
      keep that in mind for future market releases
      also using rectangles is good for prototyping , but if you wanna release a game get real art

    • AndEngine currently has 2 branches , AndEngine GLES2.0 and AndEngine Anchorcenter , if you are using Anchorcenter then it’s using a different coordinate system, you can either switch to the other branch or read this tutorial —> http://www.matim-dev.com/gles2-anchor-center.html
      which explains the differences between both versions and change the code accordingly , shouldn’t be a very hard thing
      good luck 😀

      • Yes that was it, didn’t realize I was using the other branch. Thanks and I went through the tutorial and that was fun! Good job on it and thanks for educating me on andEngine. Might give it a go for a fun test game.

  54. Amazing work! But im noob with this and im having a doubt. Can this game be changed to work with the touch and drag system used in the ninja game? Im trying it introducing the IOnAreaTouchListener in the Ship class, and then overriding the onAreaTouched method. I dont know if this is the correct method. Thanks for the tutorials, theyre very helpfull.

  55. Hy,

    If you leave the particles for a longer time, you realise, that they are moving with the enemy layer. That’s not too “awsome”. So I updated the call of the “createExplosion()”.
    createExplosion(
    e.sprite.getX() + e.sprite.getWidth()/2 + e.sprite.getParent().getX(), //Add the parent’s actual X position
    e.sprite.getY() + e.sprite.getHeight()/2 + e.sprite.getParent().getY(), //Add the parent’s actual Y position
    e.sprite.getParent().getParent(), //The target is the EnemyLayer’s parent
    BaseActivity.getSharedInstance());

    Plus, I made some changes to the particle systems rectangle. It changes color from Green to Red
    @Override
    public Rectangle create(float pX, float pY) {
    Rectangle rect = new Rectangle(posX, posY, 10, 10, activity.getVertexBufferObjectManager());
    rect.setColor(Color.GREEN);
    rect.registerEntityModifier(new ColorModifier(0.2f*mTimePart, Color.GREEN, Color.RED));
    return rect;
    }

  56. thank Jim, great tutorial. But can u help me, i can’t get position Enemy as Ship, can u introduce me , thank u very much

  57. Great tutorial, Jim \o/
    I’m beginning with android games, and your code showed me how to is simple to develop a game. Now I’ll try to modify the code and improve some things: for start, sounds and scoreboard saved on database, and then I’ll have a awesome idea to the game hahaha
    After finished, I’ll send the link to download the game
    Thanks man!

  58. Hello, I’ve noticed after adding the particle part that if you quit the game while particles are on the screen, it crashes instead of closing safely.

    It throws me indexOutOfBoundsException. Probably because of the for loop in GameScene’s detach method but I’m not sure how to repair this.

    I’ve noticed other discrepancies but I figured you’ve put them there to make sure we were following.

    Anyhow, thanks a lot for the tutorial; this is really being helpful for me to get started with andEngine.

  59. well…i am new to programming thingie and just doing it for hobby thingie :P…but have to say commendable efforts and interactive and informal language makes your blog stand out…keep up the good work

  60. My ship is on top of the screen shooting down and the enemies are not placed correctly. I assume the Y coord is different (0,0 == top_left not bottom left?). however thanks for the tutorial.

    • You are using the new Anchor-center branch of AndEngine that’s why
      This tutorial is kinda outdated, they changed their coordinate system in that branch, so that’s why 😀

    • Here is my fix it for the new coordinate system. Hope this helps for updating this tut.
      You just have to replace the the old code with this – good luck:

      // SHIP

      // constructor
      sprite.setPosition( (mCamera.getWidth() / 2), (sprite.getHeight() + 10));

      // shoot method
      MoveYModifier mod = new MoveYModifier(1.5f, b.sprite.getY(), (mCamera.getHeight()+b.sprite.getHeight()) );

      // moveShip method
      int lL = (int) sprite.getWidth();

      // ENEMYLAYER
      // restart method (without enemy fly-in animation)

      public void restart(){
      enemies.clear();
      clearEntityModifiers();
      clearUpdateHandlers();

      for (int i = 0; i < enemyCount; i++) {
      Enemy e = (Enemy) EnemyPool.sharedEnemyPool().obtainPoolItem();

      float finalPosX = 50+ (BaseActivity.CAMERA_WIDTH / 8) * (i % 6);
      float finalPosY = (BaseActivity.CAMERA_HEIGHT – e.sprite.getHeight()*4) – ((int) (i / 6)) * e.sprite.getHeight() * 2;

      e.sprite.setPosition(finalPosX, finalPosY);
      attachChild(e.sprite);
      enemies.add(e);

      setVisible(true);
      setPosition(0,0);

      MoveXModifier movRight = new MoveXModifier(1, 50, 120);
      MoveXModifier movLeft = new MoveXModifier(1, 120, 50);
      MoveYModifier moveDown = new MoveYModifier(1, 30, 100);
      MoveYModifier moveUp = new MoveYModifier(1, 100, 30);

      registerEntityModifier(new LoopEntityModifier(
      new SequenceEntityModifier(movRight, moveDown, movLeft, moveUp)));

      }
      }

  61. The detach method you create to fix the bug works sometimes, because if game is running and you press desktop button instead back button the method onBackPress is not called. You better call detach method in onPauseGame method from BaseActivity, or just call System.exit(0);

    Congratulations for this tutorial, it helped me a lot and made me laugh sometimes =D

Leave a reply to JiMMaR Cancel reply