Using Timer's - Sprite Spawn Example

  ... tutorials on how to use AndEngine.

Using Timer's - Sprite Spawn Example

Postby Mimminito » Fri Aug 27, 2010 9:36 pm

Well we are back for yet another tutorial. This time its going to be on the subject of Timer Handlers, and how you can use them within your game.

So, what is a Timer Handler? Basically you can create a Timer Handler to allow your game to perform specific actions after a certain amount of time. When you register this Timer Handler with AndEngine, it will perform a callback once the specified time has been reached.

So, where can we use this sort of functionality? Well I use this in my Explosion Live Wallpaper (go check it out and download, its free!) to spawn the explosions at certain intervals, which the user can set. I was asked to create this tutorial to show you how you can spawn a new sprite on your screen once the timer has fired its callback. So lets check out the code!

First off, lets create a basic method which will create a Sprite for us:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. /**
  2.  * Create a Sprite at a specified location
  3.  * @param pX is the X Position of your Sprite
  4.  * @param pY is the Y Position of your Sprite
  5.  */
  6. private void createSprite(float pX, float pY) {
  7.         Sprite sprite = new Sprite(pX, pY, this.mSpriteTextureRegion);
  8.         this.mEngine.getScene().getTopLayer().addEntity(sprite);
  9. }
Parsed in 0.031 seconds, using GeSHi 1.0.8.4


Ok now that we have that, lets create another method which will create our Timer Handler, and register it with the Engine:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. /**
  2.  * Creates a Timer Handler used to Spawn Sprites
  3.  */
  4. private void createSpriteSpawnTimeHandler()
  5. {
  6.         TimerHandler spriteTimerHandler;
  7.        
  8.         this.getEngine().registerUpdateHandler(spriteTimerHandler = new TimerHandler(mEffectSpawnDelay, new ITimerCallback()
  9.         {                      
  10.             @Override
  11.             public void onTimePassed(final TimerHandler pTimerHandler)
  12.             {
  13.  
  14.             }
  15.         }));
  16. }
Parsed in 0.031 seconds, using GeSHi 1.0.8.4


Take a look at the code above. Its quite simple really. All you do is create a new TimerHandler and register it with the Engine, and the code above does it all in one smooth swoop! If you take another look at the creation of the TimerHandler, you see it takes two parameters. The first is the pTimerSeconds parameter, which is just the length of time before the TimerHanlder sends its callback. This leads us onto the second parameter, which is an ITimerCallbak. This is what gets fired when your timer has finished.

So, how about creating that sprite now? Edit your createSpriteSpawnTimeHandler() method so it looks like the following:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. /**
  2.  * Creates a Timer Handler used to Spawn Sprites
  3.  */
  4. private void createSpriteSpawnTimeHandler()
  5. {
  6.         TimerHandler spriteTimerHandler;
  7.        
  8.         this.getEngine().registerUpdateHandler(spriteTimerHandler = new TimerHandler(mEffectSpawnDelay, new ITimerCallback()
  9.         {                      
  10.             @Override
  11.             public void onTimePassed(final TimerHandler pTimerHandler)
  12.             {          
  13.                 //Random Position Generator
  14.                 final float xPos = MathUtils.random(30.0f, (CAMERA_WIDTH - 30.0f));
  15.                         final float yPos = MathUtils.random(30.0f, (CAMERA_HEIGHT - 30.0f));
  16.                        
  17.                         createSprite(xPos, yPos);
  18.             }
  19.         }));
  20. }
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


If you were to run this method now, you would see your Sprite spawn after the amount of seconds you specified for the TimerHandler. But then that would be it! Its a bit dull hey, you only get one Sprite! So how about we make the TimerHandler spawn Sprites continuously everytime the TimerHandler finishes? Well, to do that, all we have to do is call reset on the TimerHandler when the callback is fired. See the final code below:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. /**
  2.  * Creates a Timer Handler used to Spawn Sprites
  3.  */
  4. private void createSpriteSpawnTimeHandler()
  5. {
  6.         TimerHandler spriteTimerHandler;
  7.        
  8.         this.getEngine().registerUpdateHandler(spriteTimerHandler = new TimerHandler(mEffectSpawnDelay, new ITimerCallback()
  9.         {                      
  10.             @Override
  11.             public void onTimePassed(final TimerHandler pTimerHandler)
  12.             {
  13.                 spriteTimerHandler.reset();
  14.                
  15.                 //Random Position Generator
  16.                 final float xPos = MathUtils.random(30.0f, (CAMERA_WIDTH - 30.0f));
  17.                         final float yPos = MathUtils.random(30.0f, (CAMERA_HEIGHT - 30.0f));
  18.                        
  19.                         createSprite(xPos, yPos);
  20.             }
  21.         }));
  22. }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


And thats it! Add these two methods into your application, modify them as needed and then call the createSpawnTimerHandler method from within your onLoadScene() method. You will have Sprites spawning randomly all over your screen at set intervals!!
---------------------------------------
Adam Goodchild
Your AndEngine Forum Moderator!
My Tutorials List
http://www.adam-goodchild.co.uk
---------------------------------------
Mimminito
 
Posts: 360
Joined: Wed Jul 21, 2010 3:08 pm
Location: Chelsmford, UK

Re: Using Timer's - Sprite Spawn Example

Postby syferz » Fri Aug 27, 2010 11:27 pm

This is exactly what I needed, thank you so much. I'll try to get the game running as soon as possible so everyone can try it out (probably sometime next week as this is my monday.
syferz
 
Posts: 10
Joined: Fri Aug 27, 2010 6:06 pm

Re: Using Timer's - Sprite Spawn Example

Postby nicolas » Mon Aug 30, 2010 3:22 am

Great job . Another way :

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. /**
  2.  * Creates a Timer Handler used to Spawn Sprites
  3.  */
  4. private void createSpriteSpawnTimeHandler()
  5. {
  6.         TimerHandler spriteTimerHandler;
  7.        
  8.         this.getEngine().registerUpdateHandler(spriteTimerHandler = new TimerHandler(mEffectSpawnDelay,true,new ITimerCallback()
  9.         {                      
  10.             @Override
  11.             public void onTimePassed(final TimerHandler pTimerHandler)
  12.             {
  13.                
  14.                 //Random Position Generator
  15.                 final float xPos = MathUtils.random(30.0f, (CAMERA_WIDTH - 30.0f));
  16.                         final float yPos = MathUtils.random(30.0f, (CAMERA_HEIGHT - 30.0f));
  17.                        
  18.                         createSprite(xPos, yPos);
  19.             }
  20.         }));
  21. }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


I have a question .
this.getEngine().registerUpdateHandler(...) and scene.registerUpdateHandler(...) is the same ?
fan Nicolas --- admin this forum (^^)
nicolas
 
Posts: 22
Joined: Thu Aug 19, 2010 5:40 am
Location: Viet Nam

Re: Using Timer's - Sprite Spawn Example

Postby Mimminito » Mon Aug 30, 2010 10:34 am

Well if you register the UpdateHandler with the Engine, it will last for the length that the Engine is "alive". But if you register it with the Scene, then if your Scene is removed, or in the background, then the UpdateHandler will not be fired. For example, you will want the FPSLogger to be run on the Engine so that its calculated throughout the lifetime of your Engine, not just a Scene!
---------------------------------------
Adam Goodchild
Your AndEngine Forum Moderator!
My Tutorials List
http://www.adam-goodchild.co.uk
---------------------------------------
Mimminito
 
Posts: 360
Joined: Wed Jul 21, 2010 3:08 pm
Location: Chelsmford, UK

Re: Using Timer's - Sprite Spawn Example

Postby syferz » Thu Sep 02, 2010 12:24 pm

"call the createSpawnTimerHandler method from within your onLoadScene() method."

so I've done this a couple different ways with my limited knowledge, my biggest problem is that:

whatever way I've tried to reference createSpriteSpawnTimeHandler() in the scene, spriteTimerHandler; is still left with a yellow line, I am not sure if I missed something else I should know.

The tutorial makes sense to me, but I still don't know where that variable is being called. also, is it suppose to be createSpriteSpawnTimerHandler()? that is what I've changed it to since the engine seems to recognize it.

is it in the engine somewhere? I've been looking for it for the last hour.
syferz
 
Posts: 10
Joined: Fri Aug 27, 2010 6:06 pm

Re: Using Timer's - Sprite Spawn Example

Postby jonny2027 » Thu Sep 02, 2010 3:36 pm

Thanks for the tutorial really useful
jonny2027
 
Posts: 17
Joined: Tue Aug 17, 2010 2:38 pm

Re: Using Timer's - Sprite Spawn Example

Postby jonny2027 » Thu Sep 02, 2010 6:33 pm

Can you post your source syferz and i will try to help
jonny2027
 
Posts: 17
Joined: Tue Aug 17, 2010 2:38 pm

Re: Using Timer's - Sprite Spawn Example

Postby syferz » Thu Sep 02, 2010 7:41 pm

This is my code, the only issue with it is that the line:
TimerHandler spriteTimerHandler;
sprite TimerHandler is yellow, if I can get this completed, I can move on to collision and then touch to move for the ship, the AI is very easy and I'll put in a background, thats the basic game, the collision will add a score and death depending on what the ship touches, but once it is done I am very close to finished with this game. Any pointers to my code would be very helpful, it's basically just the drag and drop example with this tutorial added.



Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. import org.anddev.andengine.engine.Engine;
  3. import org.anddev.andengine.engine.camera.Camera;
  4. import org.anddev.andengine.engine.handler.timer.ITimerCallback;
  5. import org.anddev.andengine.engine.handler.timer.TimerHandler;
  6. import org.anddev.andengine.engine.options.EngineOptions;
  7. import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
  8. import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
  9. import org.anddev.andengine.entity.scene.Scene;
  10. import org.anddev.andengine.entity.scene.background.ColorBackground;
  11. import org.anddev.andengine.entity.sprite.Sprite;
  12. import org.anddev.andengine.entity.util.FPSLogger;
  13. import org.anddev.andengine.input.touch.TouchEvent;
  14. import org.anddev.andengine.opengl.texture.Texture;
  15. import org.anddev.andengine.opengl.texture.TextureOptions;
  16. import org.anddev.andengine.opengl.texture.region.TextureRegion;
  17. import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
  18. import org.anddev.andengine.ui.activity.BaseGameActivity;
  19. import org.anddev.andengine.util.MathUtils;
  20.  
  21. import android.widget.Toast;
  22.  
  23. /**
  24.  * @author Nicolas Gramlich
  25.  * @since 15:13:46 - 15.06.2010
  26.  */
  27. public class game extends BaseGameActivity {
  28.         // ===========================================================
  29.         // Constants
  30.         // ===========================================================
  31.  
  32.         private static final int CAMERA_WIDTH = 720;
  33.         private static final int CAMERA_HEIGHT = 480;
  34.  
  35.         // ===========================================================
  36.         // Fields
  37.         // ===========================================================
  38.  
  39.         private Camera mCamera;
  40.         private Texture mShipTexture;
  41.         private Texture mCircleTexture;
  42.         private TextureRegion mShipTextureRegion;
  43.         private TextureRegion mCircleTextureRegion;
  44.        // private TimerHandler spriteTimerHandler;
  45.                 // ===========================================================
  46.         // Constructors
  47.         // ===========================================================
  48.  
  49.         // ===========================================================
  50.         // Getter & Setter
  51.         // ===========================================================
  52.  
  53.         // ===========================================================
  54.         // Methods for/from SuperClass/Interfaces
  55.         // ===========================================================
  56.         /**
  57.          * Create a Sprite at a specified location
  58.          * @param pX is the X Position of your Sprite
  59.          * @param pY is the Y Position of your Sprite
  60.          */
  61.         private void createSprite(float pX, float pY) {
  62.                 Sprite sprite = new Sprite(pX, pY, this.mCircleTextureRegion);
  63.                 this.mEngine.getScene().getTopLayer().addEntity(sprite);
  64.         }
  65.        
  66.        
  67.       //createSpriteSpawnTimeHandler;
  68.        
  69.         /**
  70.          * Creates a Timer Handler used to Spawn Sprites
  71.          */
  72.         private void createSpriteSpawnTimerHandler()
  73.         {
  74.                 TimerHandler spriteTimerHandler;
  75.                
  76.                 this.getEngine().registerUpdateHandler(spriteTimerHandler = new TimerHandler(200,true,new ITimerCallback()
  77.                 {                      
  78.                     @Override
  79.                     public void onTimePassed(final TimerHandler pTimerHandler)
  80.                     {
  81.                        
  82.                         //Random Position Generator
  83.                         final float xPos = MathUtils.random(30.0f, (CAMERA_WIDTH - 30.0f));
  84.                                 final float yPos = MathUtils.random(30.0f, (CAMERA_HEIGHT - 30.0f));
  85.                                
  86.                                 createSprite(xPos, yPos);
  87.                     }
  88.                 }));
  89.         }
  90.        
  91.         //*/
  92.         @Override
  93.         public Engine onLoadEngine() {
  94.                 Toast.makeText(this, "Touch & Drag the ship!", Toast.LENGTH_LONG).show();
  95.                 this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
  96.                 return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
  97.         }
  98.  
  99.         @Override
  100.         public void onLoadResources() {
  101.                 this.mShipTexture = new Texture(64, 64, TextureOptions.BILINEAR);
  102.                 this.mShipTextureRegion = TextureRegionFactory.createFromAsset(this.mShipTexture, this, "gfx/ship.png", 0, 0);
  103.                
  104.                 this.mCircleTexture = new Texture(12,12, TextureOptions.BILINEAR);
  105.                 this.mCircleTextureRegion = TextureRegionFactory.createFromAsset(this.mCircleTexture, this, "gfx/circle.png",0,0);
  106.        
  107.                 this.mEngine.getTextureManager().loadTextures(this.mShipTexture,this.mCircleTexture);
  108.                
  109.         }
  110.  
  111.         @Override
  112.         public Scene onLoadScene() {
  113.                 this.mEngine.registerUpdateHandler(new FPSLogger());
  114.                
  115.                
  116.                
  117.                 final Scene scene = new Scene(1);
  118.                 scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
  119.  
  120.                
  121.                 final int centerX = (CAMERA_WIDTH - this.mShipTextureRegion.getWidth()) / 2;
  122.                 final int centerY = (CAMERA_HEIGHT - this.mShipTextureRegion.getHeight()) / 2;
  123.                 final Sprite Ship = new Sprite(centerX, centerY, this.mShipTextureRegion) {
  124.                         @Override
  125.                         public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
  126.                                 this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
  127.                                 return true;
  128.                         }
  129.                 };
  130.                 Ship.setScale(1);
  131.                 scene.getTopLayer().addEntity(Ship);
  132.                 scene.registerTouchArea(Ship);
  133.                 scene.setTouchAreaBindingEnabled(true);
  134.                 createSpriteSpawnTimerHandler();
  135.                 return scene;
  136.         }
  137.  
  138.         @Override
  139.         public void onLoadComplete() {
  140.  
  141.         }
  142.  
  143.         // ===========================================================
  144.         // Methods
  145.         // ===========================================================
  146.  
  147.         // ===========================================================
  148.         // Inner and Anonymous Classes
  149.         // ===========================================================
  150. }
Parsed in 0.059 seconds, using GeSHi 1.0.8.4
syferz
 
Posts: 10
Joined: Fri Aug 27, 2010 6:06 pm

Re: Using Timer's - Sprite Spawn Example

Postby Mimminito » Thu Sep 02, 2010 8:31 pm

Well, two things. The first is yes its probably a typo on my behalf, and the method should be named how you have done it.
Secondly, you are never using the spriteTimerHandler as you are creating a new one in your method. Do the following:

1. Uncomment the TimerHandler spriteTimerHandler line
2. Change your method to the following:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         private void createSpriteSpawnTimerHandler()
  2.         {
  3.                
  4.                 this.getEngine().registerUpdateHandler(spriteTimerHandler = new TimerHandler(200,true,new ITimerCallback()
  5.                 {  
Parsed in 0.036 seconds, using GeSHi 1.0.8.4
---------------------------------------
Adam Goodchild
Your AndEngine Forum Moderator!
My Tutorials List
http://www.adam-goodchild.co.uk
---------------------------------------
Mimminito
 
Posts: 360
Joined: Wed Jul 21, 2010 3:08 pm
Location: Chelsmford, UK

Re: Using Timer's - Sprite Spawn Example

Postby syferz » Thu Sep 02, 2010 9:17 pm

Ok so I uncommented line 44: private TimerHandler spriteTimerHandler;
and then deleted line 74 so that that sniplet of code is the same, but now line 44 is giving me the same problem as line 74 did before. it's just saying that it's unused, and I don't know why that is since I thought we grabbed it with line 4 of the code sniplet.

I always thought that was the case, but it doesn't seem to be, I'm sorry I know this is simple code, my knowledge of coding and android just doesn't run deep enough to fix this problem on my own. I am appreciative of your help though, as I've been following your other tutorials and they have been a great help to me in learning android.

Edit: wait that line is just to register it, ok so I am just not calling this method, I'll try to figure out where I should call it from, also when I added the reset(); to the code, it is being used, but doesn't have an original call. I know this is my issue, I am trying to figure out how to call it now.
Last edited by syferz on Thu Sep 02, 2010 9:54 pm, edited 1 time in total.
syferz
 
Posts: 10
Joined: Fri Aug 27, 2010 6:06 pm

Next

Return to Tutorials

Who is online

Users browsing this forum: Exabot [Bot] and 17 guests