Aaaaaand I finally managed to start writing this tutorial .. sorry for the delay [was busy wasting my time and others’ too].
if you haven’t checked my previous 2 tutorials, you may need to do so to keep up, this tutorial will continue after my second one:
1 – AndEngine Simple Android Game Tutorial
2 – Simple AndEngine Game V1.5 [using pools]
This tutorial will cover:
– Moving Sprites with touch [follow your finger]
– Animating Sprites [AnimatedSprite]
– Enabling MultiTouch
– Simple Cooldown class
– Moving background [AutoParallaxBackground]
If you lost your project or modified it, you can download the one I provided at the end of the pools tutorial which I’ll base my tutorial on.
One final note, the Sprites I’m providing will be to support the hdpi resolution [480*800 to be precise] and may not [won’t] look good on other resolutions.
[Note: while changing sprites your game my crash , right click on your project and refresh then click on project -> clean project].
Now that’s all clear, let’s get started.
Follow Me !
The ninja is bored, The ninja wanna move, The ninja gets what he wants, The ninja should move.
Before we start, I suggest you comment out the method call for fail() so you don’t get it while testing.
We want to make our ninja follow the touch finger when we drag it, and it will only move on the y-axis [only up and down].
Go to your onLoadScene() method and scroll down to the deceleration of player and change it to.
player = new Sprite(PlayerX, PlayerY, mPlayerTextureRegion) { public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY) { this.setPosition(this.getX(), pSceneTouchEvent.getY()- this.getHeight() / 2); return true; } };
We made the player’s sprite a TouchArea [overriden the onAreaTouched of the Sprite class] it change it’s position to where the finger is dragging it.
then add those two lines.
mMainScene.registerTouchArea(player); mMainScene.setTouchAreaBindingEnabled(true);
The first registers the player as a touchArea for the scene, without the second line the sprite won’t follow you when your finger drags fast, you may try to run the game without the second line and see how it behaves.
Now you may run your game and move your mighty ninja !
Your ninja now follows your finger, you’ll notice that you cannot shoot while moving the ninja as we haven’t enabled multiTouch yet, you’ll also notice that the bullets are acting weirdly.. so let’s solve that one first.
The problem is with our [my] usage of the pool, we were creating the objects with the base position of the player , and when the bullet is reused it starts from the same base position of when it was created, let’s fix that and clean some stuff up while we are at it.
[Optional] Open your ProjectilePool class and modify your onAllocatePoolItem() to return a sprite at position 0,0
return new Sprite(0, 0, mTextureRegion.deepCopy());
Then now you can remove the static deceleration from the player [check your player sprite deceleration] and can put it back to private.[/Optional]
Go to shootProjectile method and after obtaining the projectile from the pool , change it’s position to the player’s position.
projectile.setPosition(player.getX() + player.getWidth(), player.getY());
This should fix the issue for you, back to throwing proper bullets.
Can’t move and throw at the same time ? I’m a freakin ninja !! [MultiTouch]
Calm down, we’ll get to that now, AndEngine doesn’t support multi touch by itself , you’ll need to download an extension for it.
Remember how we downloaded the AndEngine source code ? you can do the same thing with the multiTouch from this link and create your own jar file , I did face some trouble doing that but ended with a jar file of my own which you can use.
As before, put it in your lib folder and in eclipse right click on it build path -> add to build path.
You’ll also need to remove the andengine.jar file [if you are using my jar file] as mine contains the andengine too
Right click on your project -> properties -> Java Build Path , and remove the andengine.jar file.
Enabling MultiTouch is pretty easy, first we need to modify a li’l bit of what we did before , go to your onLoadEngine() method and modify the return statement it to become:
final Engine mEngine = new Engine(new EngineOptions(true,ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(cameraWidth, cameraHeight), mCamera).setNeedsSound(true).setNeedsMusic(true)); return mEngine;
This way we can modify the engine before sending it, now to enable multiTouch put this directly above the return statement:
// enabling MultiTouch if available try { if (MultiTouch.isSupported(this)) { mEngine.setTouchController(new MultiTouchController()); } else { Toast.makeText(this,"Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)",Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this,"Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)",Toast.LENGTH_LONG).show(); }
[hint: if you pasted the above code and using eclipse then use the shortcut ctrl+shift+o to auto import].
If your device doesn’t support multitouch, this will show you a message telling you that and falls back to single touch, avoiding crashing.
You may test again and see that you can now move and shoot at the same time, if you are seeing some abnormal behavior when multi touching it’s because your phone got issues [htc ?] this works fine on my Galaxy S I9000 but doesn’t act properly on a nexus one though.
Hold Fire ! [CoolDown]
Not sure if this is the proper naming for this, but I’ll use it anyway.. CoolDown.
If you played around with what you have now , you’ll notice that if you tap with 2 fingers , you get 2 bullets .. and if your phone supports multiTouch properly you can get a high number [I could get 5 bullets at a time], so we need to solve that.
The Solution that I came with was to add a delay not allowing more than one bullet to be issued during a certain period , it’ll also make the game a li’l bit harder so you’d stop spraying bullets all over the place [your ninja doesn’t like that].
Create a new class and call it “CoolDown” then paste the following:
public class CoolDown { private boolean valid; private Timer timer; private long delay = 100; private static CoolDown instance = null; public static CoolDown sharedCoolDown() { if (instance == null) { instance = new CoolDown(); } return instance; } private CoolDown() { timer = new Timer(); valid = true; } public boolean checkValidity() { if (valid) { valid = false; timer.schedule(new Task(), delay); return true; } return false; } class Task extends TimerTask { public void run() { valid = true; } } }
Even though this is a java thingie and not quite related to AndEngine directly, I’ll still explain it though.
I wanted to create a singleton class, so you only have one instance of this type in your whole program [special thanks to Mazyod, check out his blog, he blabbers about lots of useless stuff] thus it explains the sharedCoolDown() method behavior [and why the constructor is private].
You call checkValidity() it should return to you true if you can have a bullet and false if you can’t, the valid flag is the one that decides it, if it’s true then it gets toggled and a timer gets a new Task that runs after a certain delay , 100ms in our case here [you can change that if you want] and then returns true telling you that you can have a bullet.
Task is a class that extends TimerTask, it just makes valid true again when called [will be called by the timer after 100ms].
Now go back to your shootProjectile() method and add this at the top of the method.
if (!CoolDown.sharedCoolDown().checkValidity()) { return; }
That snippet just returns if you want to shoot a projectile while still on the countdown ditching the call.
No More Ghosts ! Braaa~ains ! [AnimatedSprite]
Well .. I asked my awesome friend Hashimoto (@HHajyah) to draw some sprites for me and he did an amazing job, and because zombies are awesome we will have our ninja kill some zombies [also special thanks goes to ZHA for making the sprites into proper sprite sheets] I suck at graphics 😛
I got 2 versions , one with a height of 100px and one with a height of 50px , if you are using an hdpi device [800 x 480] or higher then use the 100px sprites , else use the 50px sprites.
Save them into your /assets/gfx/ director and rename them to “target.png” and delete the old ghosts sprites.
As you can see , this is a walking zombie , so it should be animating .. let’s get started on that !
[Note: if you want to use your own sprites , you have to make sure that your sprite sheet is properly indented as that AndEngine cuts the images automatically].
Change the type of the “mTargetTextureRegion” from “TextureRegion” to “TiledTextureRegion” and declare a new variable of type “BitmapTextureAtlas” called “sheetBitmapTextureAtlas”.
private BitmapTextureAtlas sheetBitmapTextureAtlas; private TiledTextureRegion mTargetTextureRegion;
Then in onLoadResources() , initialize the sheetBitmapTextureAtlas.
sheetBitmapTextureAtlas = new BitmapTextureAtlas(512, 512);
The change the initialization of the texture region to the following:
mTargetTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(sheetBitmapTextureAtlas, this,"target.png", 0, 0, 3, 1);
We just loaded the image properly and told AndEngine that we have 3 columns and 1 row so it can cut it down into 3 images properly.
Now have the Engine load the textures:
mEngine.getTextureManager().loadTexture(sheetBitmapTextureAtlas);
And let’s proceed to the TargetsPool class and make some simple modifications changing to TiledTextureRegion and AnimatedSprites instead of TextureRegion and Sprites:
public class TargetsPool extends GenericPool { private TiledTextureRegion mTextureRegion; public TargetsPool(TiledTextureRegion mTargetTextureRegion) { if (mTargetTextureRegion == null) { throw new IllegalArgumentException("The texture region must not be NULL"); } mTextureRegion = mTargetTextureRegion; } protected AnimatedSprite onAllocatePoolItem() { return new AnimatedSprite(0, 0, mTextureRegion.deepCopy()); } protected void onHandleRecycleItem(final AnimatedSprite target) { target.clearEntityModifiers(); target.clearUpdateHandlers(); target.setVisible(false); target.detachSelf(); target.reset(); } }
You’ll need to fix everything related too , change every Sprite object used with the targets to AnimatedSprite including the linkedlists you have then inside your addTarget() method and before attaching the target to the scene add this line:
target.animate(300);
Which animates the target for you , you can change the number to change the animation speed to whatever you want.
Those Are NOT Shurikens !! [Sprite Modifiers]
Hide your kids , hide your wife , the ninja noticed that he’s throwing fake shurikens and will go on an ALL CAPS RAGE !!!
let’s give him real shurikens shall we ? As before, there are 2 versions of the Sprite:
assets/gfx , rename to “projectile.png” and delete the old one this just changes the projectile sprite , if you wanna test then go ahead but it ain’t worth it .. not yet at least.
proceed to shootProjectile() and swap the MoveModifier you have with this MoveByModifier:
MoveByModifier movMByod = new MoveByModifier(realMoveDuration, realX, realY);
The difference is that this one doesn’t take the movement’s start point , it moves the sprite from wherever it is to that point .. this will prove to be useful later on.
No respectable shuriken gets thrown without being rotated , so we’ll have to add this line too:
LoopEntityModifier loopMod = new LoopEntityModifier(new RotationModifier(0.5f, 0, -360));
LoopEntityModifier takes an EntityModifier and keeps on looping on it, if you didn’t specify a count then it’ll keep on doing this till the end of time .. in another word .. it’s a while(true) with no breaks or exists !! [i.e infinite loop].
So we provide the loopMod with a RotationModifier which will rotate from degree 0 till degree -360 [counter clock-wise] in half a second, the loop will make sure that this happens till infinity [and beyond !!].
One last Modifier is needed which is called ParallelEntityModifier:
final ParallelEntityModifier par = new ParallelEntityModifier(mod, loopMod);
This one runs couple of modifiers in parallel [duh !] so we added our movByMod and the loopMod so we get the rotation effect while the shuriken is thrown.
Now just make sure you register the new modifier and then run !
projectile.registerEntityModifier(par.deepCopy());
Sayonara Ninja-sama [New Hero]
The ninja has reached the end of his journey, it’s time for goodbye .. and to introduce our new hero.
THE URBAN NINJA !! [he’s still a ninja somehow !].
2 versions of the sprite sheet for you , here you go 😀
Put it in the assets/gfx director and name it “hero.png” [the name player is still dedicated to our old ninja , can’t be reused or he’ll get mad].
You’ll also have to change the deceleration for the sheetBitmapTextureAtlas to:
sheetBitmapTextureAtlas = new BitmapTextureAtlas(2048, 512);
Introduce a new “TiledTextureRegion” and an animatedSprite:
private TiledTextureRegion mHeroTextureRegion; public AnimatedSprite hero;
Then inside onLoadResources() [notice we have 11 columns here, keep that in mind for now]:
mHeroTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(sheetBitmapTextureAtlas, this,"hero.png", 0, 212, 11, 1);
Remove the old “mPlayerTextureRegion” and start fixing the code, remove it from onLoadResources first , then in onLoadScene , fix the PlayerX and PlayerY to these:
final int PlayerX = (mHeroTextureRegion.getWidth() / 20); final int PlayerY = (int) ((mCamera.getHeight() - mHeroTextureRegion.getHeight()) / 2);
There is no exact reason for the /20 , I just put there cause it looked nice on my screen 😀
We’ll have a new AnimatedSprite instead of the old Sprite [which you will have to delete].
hero = new AnimatedSprite(PlayerX, PlayerY, mHeroTextureRegion) { public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) { this.setPosition(this.getX(), pSceneTouchEvent.getY()- this.getHeight() / 2); return true; } };
Now delete the deceleration for the Sprite player, and replace it’s occurrence in the code with hero [also remove the setScale if you have it]
Go the end of shootProjectile() and add this line:
hero.animate(50, false);
Which animates the hero, giving 50ms for each frame and only happens once [looping is set to false] , now’s a good time to modify the CoolDown class changing the delay to 600.
We have 11 frames , each is 50ms that’s 550ms , let’s add another 50ms which gives us the 600ms CoolDown duration , making sure we don’t cut down the animation in the middle , test and see how your hero ninja animates when throwing.
How Come He’s Throwing Before Throwing ? [some clean ups]
If you are actually following this tutorial and writing the code instead of just reading and pretending that you know everything and it’d be easy to write this cause you are awesome anyway ..
You’d have noticed that the shuriken gets thrown before the animation finishes , we don’t want that , do we ?
To be honest, I wasn’t exactly sure how to solve this, and did create some kind of a work around .. not sure if it’s the best method or not , but it worked so I’m happy and I don’t care what you think.
The idea here is , add the projectile on touch but make it invisible, then wait for a certain delay then make it visible and start animating it, so our whole work will be inside the shootProjectile() method.
After the ParallelEntityModifier deceleration , add this new modifier:
DelayModifier dMod = new DelayModifier(0.55f);
Which is a delay for 0.55s [not ms].
Then we’d have to add something called IModifierListener which gives you 2 methods that gets called before and after the modifier starts working, it’ll be like this:
dMod.addModifierListener(new IModifierListener() { @Override public void onModifierStarted(IModifier arg0, IEntity arg1) { } @Override public void onModifierFinished(IModifier arg0, IEntity arg1) { shootingSound.play(); projectile.setVisible(true); projectile.setPosition(hero.getX() + hero.getWidth(), hero.getY()+ hero.getHeight() / 3); projectilesToBeAdded.add(projectile); } });
You’ll also have to change the projectile’s Sprite to final, notice that we are setting the projectile’s position AFTER the delay is done.. if you didn’t do that then when you click and move the hero , the projectile will start moving from where hero was when you clicked not when the animation finished.
Also we are adding the projectile to the linked list here to avoid zombies dying from hitting the projectile before it goes visible, make sure you remove the linkedList addition from the end of shootProjectile() method [don’t add the same projectile twice !!!].
We’ll use one last modifier called SequenceEntityModifier which takes some modifiers and runs them one after the other , so your last lines in the shootProjectile() method will be [make sure you remove the old attachChild on top]:
SequenceEntityModifier seq = new SequenceEntityModifier(dMod, par); projectile.registerEntityModifier(seq); projectile.setVisible(false); mMainScene.attachChild(projectile,1);
This should fix it for you, enjoy the perfect effect !
Move Move Move [AutoParallaxBackground]
This part will have a little issue, the images I created [yes I drew them with microsoft paint :P] are taken into consideration that the screen size is 800*480 , if you have a smaller screen then you may need to create your own image [or scale the ones I’m providing] if you want everything to appear perfect if not then you can set the camera width and height to static values and the openGL will scale everything up or down to fit into the screen.
I created 2 images , use whichever you like:
The Images resolution is 1100*480 , I did make the width bigger than the screen size so you don’t show the whole image at once , we’ll let the image scroll to give a moving effect for the hero.
Put whichever background you prefer in the assets/gfx directory and rename it to “background.png”.
Declare those new objects:
private BitmapTextureAtlas mAutoParallaxBackgroundTexture; private TextureRegion mParallaxLayer;
Go to onLoadResources() and put this in:
mAutoParallaxBackgroundTexture = new BitmapTextureAtlas(1024, 1024,TextureOptions.DEFAULT); mParallaxLayer = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this,"background.png", 0, 0);
Don’t forget to load the texture into the engine at the end of this method. [make sure the mParallaxLayer line is added AFTER setting the path for the BitmapTextureAtlasTextureRegionFactory].
Navigate to onLoadScene() and those lines inside:
// background preperations final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 10); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-25.0f, new Sprite(0,mCamera.getHeight() - this.mParallaxLayer.getHeight(),this.mParallaxLayer))); mMainScene.setBackground(autoParallaxBackground);
Also remove the old setBackground we had.
In the above code, we created a new AutoParallaxBackground that changes on a rate of 5 parallex and we attached the background image and set it to go on a speed of -25 [move from right to left], mess around with it and see what you get 😀
Wrap Up [and code]
That ends the second tutorial , hope it was clear enough .. drop a comment when you are done reading , it gives me that nice feeling that someone is actually reading this and that it’s useful 😀
After I finished this I noticed that the position of the throwing was kinda off, maybe I’ll check that later on .. I’ll stop writing those tutorials for a while now till I finish my other projects, if you fixed the issue then drop a comment and I’ll update the post [and credit you too]. commenter “Diego” kindly provided the fix to this issue , check his fix in the comments below.
Also if you are an artist and would like to share sprites [or at least a proper background that’s not ugly and not made using Microsoft paint :P] drop them in the comments below and readers would rejoice [or something].
If there are any issues in the tutorial , let me know.
And here’s the Source Code I didn’t get to add lots of comments on it .. but I think it should be clear if you read the tutorial, you can use this however you want, but please give credit for that [If you made a game and released it on the market based on this one tell me, I’ll be happy to check it out :D]
1: —– autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(+25.0f, new Sprite(0,mCamera.getHeight() – this.mParallaxLayer.getHeight(),this.mParallaxLayer)));
mMainScene.setBackground(autoParallaxBackground);
* Please tell how to fir the screens hight and width Mainly the height (It must do it auto, thanks
2: —— mAutoParallaxBackgroundTexture = new BitmapTextureAtlas(1024, 1024,TextureOptions.DEFAULT);
* What does the 1024 , 1024 do? because it will crash if values changed thanks :)!
and very good job on these tutorials!
To auto fit the resolution, you have to set the camera height and width manually to certain sizes [just like how the AndEngine tutorials are doing]
You can have 2 final variables at the top
from the andEngine tutorials , they use these
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
you’d have to set the width to 800 if you wanna use the background I provided
and inside onLoadEngine() you’d have to replace the camera line with this one
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
This should do it regarding the scaling for the game on all resolutions [I didn’t try that but that’s what the “internet” said :P]
[note: I’m using -25.0f and yours says +25.0f, if you wanna get the correct effect change that to -]
for the second question , those numbers are the size that the texture atlas takes from the ram, they should be a power of 2 [2,4,8,16,…512,1024…etc] and your image should fit in , in my case the background’s resolution is 1100*480 so taking 1024 won’t fit , you’d have to go to the next number which is 2048
😛 Thank YOU! I think I saw the fixed camera before just didn’t think back! anyway thanks 😀 now My game is all good :)!!, Il post a link when its complete, but first 4 assignments for college :P.
This should fix the stars being off.
private void shootProjectile(final float pX, final float pY) {
if (!CoolDown.sharedCooldown().checkValidity()) {
return;
}
int offX = (int) (pX – (hero.getX() + hero.getWidth()));
int offY = (int) (pY – (hero.getY() + hero.getHeight()/3));
if (offX <= 0)
return;
final Sprite projectile;
projectile = pPool.obtainPoolItem();
int realX = (int) (mCamera.getWidth() – (hero.getX() + hero.getWidth()) + projectile.getWidth());
float ratio = (float) realX / (float) offX;
int realY = (int) ((offY * ratio));
float length = (float) Math.sqrt((realX * realX)
+ (realY * realY));
I simplified it a bit by getting rid of offReal and made the stars appear closer to where the star is in the animation. Not sure if it works on other resolutions.
Thanx for this man , you are awesome ! [I didn’t test it though :P]
Hi
you forget to close else
// enabling MultiTouch if available
try {
if (MultiTouch.isSupported(this)) {
mEngine.setTouchController(new MultiTouchController());
} else {
Toast.makeText(this,”Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)”,Toast.LENGTH_LONG).show();
} catch (final MultiTouchException e) {
Toast.makeText(this,”Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)”,Toast.LENGTH_LONG).show();
}
Thanks for noticing that, got it fixed
I’m trying to import de source code to my Eclipse + Android SDK, but it doesn’t work.
please make sure that everything is installed properly before attempting to do so
check the first tutorial https://jimmaru.wordpress.com/2011/09/28/andengine-simple-android-game-tutorial/
and follow the links in the “preparing your tools” section to make sure everything is working properly
Thanks for the quick response. My SDK works good, but i have problems importing that code. First of all, this: [2012-01-04 12:47:00 – AndEngine Tutorial V2.0] Unable to resolve target ‘android-4’
And there are any red lines in code, like overrides and imports.
That error is probably because I’m using an sdk that you don’t have, right click on your project then go to properties then chose android and chose which target you want to build against [android -4 is sdk 1.6 which am using here] or you can download the 1.6 sdk.
you can remove the override annotations (@override) if you want, also from the link in the first tutorial just make sure that AndEngine is working properly
I am really excited to try this out! Thanks for this tutorial 🙂
Thank you very much for your tutorial! It’s very useful and helps me a lot:)
Thanx man. This was really awesome! Keep up the great work!
This has been a great tutorial, and very fun to work with. One question I have, is how would you go about making an animated explosion to go with the collision of the target? Creating a new sprite doesn’t make a lot of sense. I suppose that somehow you would load up other images from the same or different sprite sheet and change the tile index?
Does anyone have any thoughts or examples of this?
Thanks a bunch!
I’m glad you liked it, you can use an explosion pool and add a new sprite to get the explosion effect
if anyone got any other idea then please state it here 😀
JimmAr, you’re comment as simple as it was, was very helpful. Thanks. I was able to accomplish what I was looking for!
Im trying to add an effect when the targets hits the player that the player will loose health.I got an image for the heart but im struggling just to get the image on the screen. I have followed this tutorial but just dont get it working! i have an idea for the code.
I’m planning on adding a similar effect on the next tutorial , but I can’t say when I’ll even start working on that [pretty busy lately >_<]
but I think that you just need to add your heart sprite over the player's sprite, just make sure that the sprite doesn't get covered by any other sprite [look up at the z depth for sprites]
Thanks for the tutorial, I was lost in AndEngine and with this tutorial, I learned so much things.
Tomorrow I want to refactor the code, to let it a bit more OO. I can post the project here if someone wants :).
If you want help with the next tutorial, let me know, I will try to help with I can.
Again, thanks for the tutorial, was well detailed and step by step.
I didn’t make it OO because I thought that having everything in one file would be better for starting a tutorial [I used to hate multiple files beginners tutorials]
But I was planning on making it OO in future updates , if you did that then share the project and I will add it to the tutorial and may use it as a reference for the next one
Jimmar i don’t have words to tank you. Please, for the good of the planet, you need to keep up the good work.
you are welcome 😀
lemme just finish the project at hand then I’ll write another tutorial 😀
You are my hero. Maybe, one day, i can be like you. lol 😀
Jimmar, another question for you: i want bleed the ninja ( yes, i’m bad ), and create life for him that would be measured by hearts or something like that.
How do I bleed the ninja ? It’s possible to use the same sprite, but in another line the “bleed animation” ? If is, how i do this ?
Thank you again.
you have 2 ways of doing that
1 – have 2 animated sprites objects on top of each others , one is hidden and the other is visible , the first is the normal shooting one , and when the ninja gets hurt you hide this one and show the other one + animate() it , then hide it again and show that [unrecommended idea :P]
2 – you can create one animated sprite with multiple animations and when animating you can decide where do you want it to animate from to , check this example from the andEngine examples
https://code.google.com/p/andengineexamples/source/browse/src/org/anddev/andengine/examples/RepeatingSpriteBackgroundExample.java
notice at lines 104 -> 114 how they all have different animations on the same AnimatedSprite just by chosing where to start from and end to
Yes, i think i will do with multiple animations. Thanks for the answer. 😀
Jimmar, my master. I want to move the ninja with the Accelerometer ( only up and down ). You have any tutorial or examples ? Thank you !!!
lol master XD
I haven’t played with the accelerometer before , but I did find this code in the forums
http://www.andengine.org/forums/tutorials/moving-a-sprite-with-the-accelerometer-sensor-t1223.html
you should be able to change it so it only moves up and down
Hey Jim, i am having problem on the import.org.anddev.andengine.opengl.texture.atlas where it shows red underline. It says org.anddev.andengine.opengl.texture.atlas cannot be resolved. Any solution?
umm , did you manage to go through the first tutorial ?
are you sure that andEngine is working correctly ? if not then check the links I provide at the top of the first tutorial they contain how to do that
if you did all that , then try cleaning your project and restarting eclipse see if that helps or not
Master, the example works great. But i have one question ( no ! what a surprise ).
I don’t know what version of “AndEngine.jar” i use. In your example, functions like: mMainScene.attachChild(target); works great. But in this example of accelerometer, he use:
scene.getTopLayer().addEntity(sprite); And attachChild not work.
I’m a little lost here, and i need your help, Master !!!
apparently they deprecated getTopLayer() , attachChild should work fine
but there are some changes you need to do for the texture too
this is a full working modified code [also changed resolution width to 800 😛
http://pastebin.com/vSsDiTBc
it should work [just make sure you put the proper image in it]
Thanks again, Master.
You are great ! So i think i just have to continue using the andengine.jar where methods like attachChild works. 😀
Hi Jimmar,
Please forgive my poor english and let me congratulate you for your outstanding work doing this tutorials, are really usefull and very good explained.
Just one question about the background music you are using for your tutorials, is it copyrighted or something? I’m interested on using it for a project that I’ve been working on.
Thanks again for your collaboration.
All the sprites/music in the first tutorial are made by Ray and taken from his tutorial [http://www.raywenderlich.com/352/how-to-make-a-simple-iphone-game-with-cocos2d-tutorial], he gave me permission to use them in my tutorial and I think he won’t mind you using them in yours, but you may want to ask him about them
The sprites in the second tutorial are made by my friend [except for the background which I created using paint :P] , and you can use them in whatever you want
Thank you for going through the tutorial , glad you liked it 😀
Jimmar,
All your tutorials are good congratulations, and I always EvandroWAS are tracking more posts please hug 🙂
Jimmar,
I am trying to follow your tutorials and develop the game you have described…it was all fine till the pools tutorial…the pool thing worked fine..now i am interested in using sprite sheets for the target instead of a static target..once done with that i will try to animate the player too..i followed your method but its troubling me a bit..there is no error as such but the application ForceCloses when i try to run it..it will be very kind of you if you can provide me your mail id so that i can send you the project to take a look..I am sure it wont take you more than a few minutes to figure out what is wrong with it…
thanks in advance…pls rply soon..
you can use pastebin.com to put your code and paste a link here if you want
also my email is available in the about page [link at top of the blog]
Jimmar,
i have mailed you the SlingShot.rar file (the project i mentioned)..please take a look and help me out…
thank you….please reply soon(as you always do..:)).
JiMMaR we are waiting for the new tutorial.
Please, please, pleeeeeeeeeeeeeaaaaaaaaase !!!
😀
Master, i want stop the enemies in touch event, i already have created the event, but i don’t know how stop them. Thanks again !
umm… try removing the modifier(s) from the sprites in the event, not quite sure if that works but it should
you may also need to stop the animation too
So… I used “this.clearEntityModifiers();” for stop the sprite.
But “this.stopAnimation();” not stopped the animation. Any idea ? Thanks again²
Another question. I put this.animate… In ontouch of sprite method. But i have a animation in all enemies sprites. Why? thanks again
you mean that when you touch a sprite all sprites animate ? and did you solve the stopping animation problem yet ?
also could you paste your code on pastebin.com and give me a link so I understand what’s going on
Exactly, dude. When i touch one sprite all sprites animate.
inimigo1 = new AnimatedSprite(x, y, this.mInimigo1TextureRegion)
{
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
{
this.clearEntityModifiers();
this.animate(new long[]{200, 200, 200}, 3, 5, true);
return true;
}
};
Here is my code. Any problem ?
JiMMaR, this.animate(new long[]{200, 200, 200}, 3, 5, true) don’t work only inimigo1.animate(new long[]{200, 200, 200}, 3, 5, true) but all sprites animate. And, inimigo1.stopAnimation(); and this.stopAnimation(); don’t work. =/
your problem is probably here , I mentioned this in the tutorial
inimigo1 = new AnimatedSprite(x, y, this.mInimigo1TextureRegion);
should be
inimigo1 = new AnimatedSprite(x, y, this.mInimigo1TextureRegion.deepCopy());
this should potentially solve the problem that all sprites animate together
as for the issue with stopping animation, I still didn’t mess around with that so I can’t really help you .. tell me if you found a solution though
I just found this link which explains how to use the stopAnimation() method
https://andengineguides.wordpress.com/2011/09/12/getting-started-working-with-sprites/
apparently you need to provide which frame the sprite should stop the animation at, keep on researching that though
Thanks, Jimmar. this.mInimigo1TextureRegion.deepCopy() really solved my problem. After, i just use this.stopAnimation(); and the animation stopped too. You are my hero !
😀
Master, what you’re thinking in develop for the next tutorial ?
And… Everybody wanna know: The next has date of release ?
Master, i using a basic collision detection, but i’m not using this to removesprite, i’m using to do an animation of death ( MUAHUAHUA. 😀 ). But i have a problem ( WHAT A SURPRISE ! ) i want to do the animation only in the first time when the “bullet” hit the target. Otherwise the sprite always animate, and it look’s strange a death “sprite” animate again. 😀 You know any way to know if the target has hit before ?
Like:
if (hit)
{
if(if is not hit before)
{
_inimigo.animate(new long[]{50, 50, 50, 50}, 4, 7, false);
hit = false;
}
}
Thanks²³³³, and sorry for my English.
Just add a boolean that initially is false, and when the enemy is hit simply check if the boolean is false and if it is, set it to true and then do the animation. if the enemy is hit again the boolean will be true and the animation won’t restart…
Thanks, Björn. But i have a LinkedList with a lot of enemies. And i solved the problem by other way. I just used de pool to recycle and removed the sprite from LinkedList.
The idea is just how Björn explained it
but in practice you may need to create a new monster class which contains a sprite and a boolean flag [or an int counter if you wanna do more than one hit] and your linked list would be a list of enemies instead of list of sprites
I’m kinda busy with couple of projects [and finding a job :P] so no ETA for next tutorial .. sorry
hehe. The “” stund Björn isn’t necessary since it is actually my name:) funny enough it is the Swedish word for Bear
🙂
sorry about that 😛
got it fixed now
Yes. Anyway i already have created my enemy class with attributes like life, speed, hitCount and others…
Now i wanna to know how in the game “Fruit Ninja” ( you should know) is made the cut effect when we touch the screen. There are some method with initial and final touch ?
( one video of the game: http://www.youtube.com/watch?v=tXEo-asZyBY&feature=fvst )
Thanks for the help and good luck in the “Job quest” 😀
if you want the trail effect behind the finger drag , that’s kinda too advanced for me 😛
but I think you should be able to find stuff for that if you looked [or asked at the andEngine forums]
if you just want a cut effect on a sprite , then that should be kinda doable .. but I still can’t help you in that so far
I really look for trail effect. I’ll look for the effect in And Engine Forums. And if i find, i post here.
Thanks, Jimmar.
great tutorial!!! it was exactly what I was looking for!!
It covers all the main aspects related to the game development in andengine!!
keep on good working!!!
can you help me?
I want the background to move from top to bottom!
take a look at this
http://www.andengine.org/forums/features/vertical-parallax-background-t1407.html
Thanks! 🙂
Hi Jimmar,
Thank you so much for the tutorial.
I must say this is the best tutorial on anything related to android. You have obviously explained the things very nicely, but also because you make it look so effortless and not intimidating at all. Also you make it really funny, many of the ninja stuff made me smile and I really enjoyed reading it.
I had one suggestion for you, why not consider writing a book on Andengine. I have gone through quite a few android game development books at least 4-5(I have an online subscription) and believe me they don’t even properly do what you have done in these three blog entries. I am sure you will be able to write a great one. A publisher is looking for someone to write a book http://www.andengine.org/forums/post31645.html#p31645
Thanks again for the tutorial.
I’m pretty flattered by this, but I don’t think that I’m currently qualified to write a book.
I started these tutorials as a way for me to learn and because I couldn’t find suitable tutorials for people like me, I’m planning on releasing more tutorials after I get rid of my laziness 😛
Maybe someday I’ll release a book, but not yet.. who knows
Hi Jimmar, another great tutorial. Thank you very much and keep going. 🙂
Hi Jimmar, it would be great if you could make a tutorial about moving a character on a scroll level with a chasing camera (I’m stuck on that last point…) 🙂
Hi JiMMaR, this is great tutorial. I’ve a problem: i downloaded the source code in the final but it havent AndEngineMultiTouch.jar.
How can i have it?
thanks
sorry i fix it!!
my projectile is shooting a lot lower then where i touch, how do i fix it. i have all the same code i believe.
read the wrap up section , I already noted that the solution for this is in the comments
“In the above code, we created a new AutoParallaxBackground that changes on a rate of 5 parallex and we attached the background image and set it to go on a speed of -25 [move from right to left], mess around with it and see what you get ”
Hi, can you help me to move background image from up to down or down to up instead right to left as in your tutorial
a quick google search and I found this , see if it works for you
http://www.andengine.org/forums/features/vertical-parallax-background-t1407.html
copied the code, showing some errors. please provide a good and complete andengine gles2 example. there is no complete solution on the web.
I wrote a warning on the first tutorial that this is an old outdated tutorial series for GLES1
if you want a tutorial for GLES2.0 check my other tutorial [called Jimvader] for creating a simple space invaders clone
hey man, thanks for your excellent work!
I follow you. and i wanna make a little game also.
I already create a scene where spawn sprite are comes and pass the screen. I wanna to set touch effects on every spirits which on the screen.
Where i add the touch effects for every spirits ??
Check my next tutorial called Jimvaders , I explain that there
I want to shoot the bullet from Canon with projectile motion just like Angry Birds has. Can you help in writing the code the for that I am not able to get hold of the formula and the code.
This requires you use the physics engine box2d , it’s out of the scope of this tutorial
you need to check box2d out and read the examples
ItFirst of all I really thank you for this tutorials ..I’d like to give a favor please could you upload the jar file of gles1again…. i have searching on the net but i find only one but thisis diferent that you use ib this tutorial…sorry for my english but you’re tutorial are great and i need to use my bad engliah to try to comunicate! 😉
even though I really do suggest following the jimvaders tutorial and switching to GLES2.0
I updated the links in the posts, if you go to the first tutorial you should be able to download the jar file from there
or you could download the whole project from this tutorial and extract the jar file from it
Heey “JiMMaR” your tutorial really help . i am working on a app with my friend . and i want to make it a side scoller . do you know where i can get started ? i been looking for a tutorial on a basic tmx game but i cant find anything . also how did you make your sprite sheet ? i would like to make one for my game . thanks (;
I’m glad I was any help, I haven’t used any TMX maps before.. but maybe the AndEngine examples would help you [this is for GLES2.0 but you can find the GLES1.0 version in the gles1 examples]
https://github.com/nicolasgramlich/AndEngineExamples/blob/GLES2/src/org/andengine/examples/TMXTiledMapExample.java
or you may try to contact this guy
https://sites.google.com/site/matimdevelopment/diego
his site got tutorials , and as you can see from the link he has a side scroller in the making
about the sprite sheets, I had them created manually using photoshop [my friend did it .. my photoshop skills are no better than a microwave] .. but you may try using texture packer if you want [look it up]
Hello,
First of all thank you for this awesome tutorial.
I’ve just one question : How do I do if I want the ninja to run when he’s not throwing shurikens? I suppose I need 2 animatedsprites for this, but How manage them?
Thanks in advance,
if you have them all in one sheet , you can chose which frames to animate
let’s say you have one sheet , where the first 4 frames are running , and the other 4 frames are throwing
you prepare it like this
final long[] fDurationRun = { 300, 300, 300, 300,};
final int[] framesRun = { 0, 1, 2, 3};
final long[] fDurationThrow = { 300, 300, 300, 300,};
final int[] framesThrow = { 4, 5, 6, 7};
and then when you animate the running you do
ninja.animate(fDurationRun,framesRun,true);
when you want to throw, you’ll have to
ninja.stopAnimation(); //not sure if this is needed , play around
ninja.animate(fDurationThrow,framesThrow,false); //false is for the loop
you might also wanna attach an animation listener so that when throwing is finished, you go back to running again
you may have a problem with the proper running animation, another solution is to have 2 sprites , one for the upper part and one for the lower part , where the lower part is always animating for the running animation and the upper part only throws, attack them together to an entity
that’s what I could think of right now, hope it helped
Thanks a lot 🙂
Hello my friend congrats for the great tutorial 🙂
I wanna know if is possible that you could teach us how to make the ninja got damage on collision. pls pls pls.
the ninja getting damage should be the same way as the zombies getting damage, if you understood the tutorial you should be able to do that yourself 😀
Tks Jimmar I already figure out how to do that 🙂 now i’m trying to do a health bar, i’m researching how to do that, but if you have some tips i’ll apreciatte, and when u have a bit of time to u spend with us 😛 please can u give some classes about box2d and how to use it, or a general view 🙂 tks in advance and really i loved your work 😛 cya
Hai guys, I have code like this
http://pastebin.com/YFhhMpxq
Can anyone help, my animateSprite can’t run whell
Please don’t paste long codes as comments , use pastebin next time
and you didn’t mention what was wrong , but you have an error here
this.asLakon.animate(new long[] { 100, 100 }, 0, 3, true);
this is wrong , it should be
this.asLakon.animate(new long[] { 100, 100 }, new long[] {0,3}, true);
this will loop over the frames 0 and 3 [it will skip frames 1 and 2] and each will get 100ms
can u correct this code,,i dont want the player to rotate.
public void createPlayer(TiledTextureRegion mCircleFaceTextureRegion, int x, int y){
mPlayer = new Player(x, y, 30,30,mCircleFaceTextureRegion, this);
FixtureDef FIXTURE = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
Body body;
//body = PhysicsFactory.createCircleBody(mPhysicsWorld, mPlayer, BodyType.DynamicBody, FIXTURE);
body= PhysicsFactory.createBoxBody(mPhysicsWorld, mPlayer, BodyType.DynamicBody, FIXTURE);
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(mPlayer, body, true, true, false, false));
scene.getTopLayer().addEntity(mPlayer);
}
I didn’t talk about physics yet and this is out of the scope of the post .. also I’m not sure what you are trying to do
I can’t help you in this .. sorry
Hello,JiMMar! I have a problem when i import your source code .Project can’t start. It notify a red exclamation mark,In java build path notify andengine mutil touch missing and com.androd.ide.ECLIPSE.adt.libarry red erro although I changed java compiler is 1.6.Can you help me?
Hey Jimmaru!
Nice tutorial btw, my game keeps crashing after adding just the background? Is there any way you can contact me like skype or?
Hi Jimmar. You tutorials are life savers from newbies like me. Thank you very much for this.
I do have a doubt. Keeping you code as base, I am trying to make a game where my player can move right using accelerometer. In my case, the enemies are coming from bottom. I use smooth camera and make it to chase player. I use parallax background. Till this point everything works fine. But firing bullets for my player is not working fine once I cross screen width and continue to move right. I tried changing shootProjectile method to give correct formX and toX value to MoveModifier but it doesn’t seem to work once player crosses screen width and continue to move.
Please advise me, what should I do.
Thanks again for the tutorial
Thanks for passing by
it seems that you managed to change this tutorial into my other tutorial 😛
https://jimmaru.wordpress.com/2012/05/19/jimvaders-my-own-invaders-clone-thingie-tutorial/
did you check that out ?
also I’m not exactly sure what your problem is , but if you are chasing the player with the camera then you better use BoundCamera and set bounds on the screen so the camera doesn’t go over the max screen width [and add some constrains to the player]
check this article regarding that
http://www.matim-dev.com/setting-camera-bounds.html
Thanks a lot for this awesome tutorial !
but there’s a problem when i try to build the project (after i add the required jar files of MultiTouch and AndEngine ) …
Unbale to execute DEX.
try to clean the project and see what happens
Thanks a lot for this awesome tutorial..but i have faced one problem when i use AutoParallaxBackground it flicker(lag) i mean it is not very smooth ..i am creating running with shooting game using your code but not able to achieve very smooth effect in background moving Please help me i searched a lot not found any solution……
Hello, JiMMaR.
Literally the way you do these tutorials are just the best. I have so much hope and you’ve made it possible for me.
May I also have a real quick request? I’ve been trying to get a FAIL if one of the targets collides with my Ninja.
//check if player hit
if (_fish.collidesWith (player))
{
fail();
hit = true;
break;
}
However, I don’t think andengine is detecting collision with my player. Can you do a real quicky. Maybe just add an extra bit. How to detect collision between a target and player?
Thank you !
ops! to be consistent with your tutorial. its supposed to be _target not _fish. Just a small experimentation for me. lol
when i run app, it is error : can anyone help me
this is LogCat
//————————
03-06 16:23:33.810: E/AndroidRuntime(18852): FATAL EXCEPTION: main
03-06 16:23:33.810: E/AndroidRuntime(18852): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.wordpress.jimmaru.tutorial.SimpleGame/com.wordpress.jimmaru.tutorial.SimpleGame.AndEngineSimpleGame}: java.lang.ClassNotFoundException: Didn’t find class “com.wordpress.jimmaru.tutorial.SimpleGame.AndEngineSimpleGame” on path: /data/app/com.wordpress.jimmaru.tutorial.SimpleGame-1.apk
03-06 16:23:33.810: E/AndroidRuntime(18852): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
03-06 16:23:33.810: E/AndroidRuntime(18852): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-06 16:23:33.810: E/AndroidRuntime(18852): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-06 16:23:33.810: E/AndroidRuntime(18852): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-06 16:23:33.810: E/AndroidRuntime(18852): at android.os.Handler.dispatchMessage(Handler.java:99)
03-06 16:23:33.810: E/AndroidRuntime(18852): at android.os.Looper.loop(Looper.java:137)
03-06 16:23:33.810: E/AndroidRuntime(18852): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-06 16:23:33.810: E/AndroidRuntime(18852): at java.lang.reflect.Method.invokeNative(Native Method)
03-06 16:23:33.810: E/AndroidRuntime(18852): at java.lang.reflect.Method.invoke(Method.java:511)
03-06 16:23:33.810: E/AndroidRuntime(18852): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-06 16:23:33.810: E/AndroidRuntime(18852): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-06 16:23:33.810: E/AndroidRuntime(18852): at dalvik.system.NativeStart.main(Native Method)
03-06 16:23:33.810: E/AndroidRuntime(18852): Caused by: java.lang.ClassNotFoundException: Didn’t find class “com.wordpress.jimmaru.tutorial.SimpleGame.AndEngineSimpleGame” on path: /data/app/com.wordpress.jimmaru.tutorial.SimpleGame-1.apk
03-06 16:23:33.810: E/AndroidRuntime(18852): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
03-06 16:23:33.810: E/AndroidRuntime(18852): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
03-06 16:23:33.810: E/AndroidRuntime(18852): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
03-06 16:23:33.810: E/AndroidRuntime(18852): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
03-06 16:23:33.810: E/AndroidRuntime(18852): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
03-06 16:23:33.810: E/AndroidRuntime(18852): … 11 more