I am creating a game using Andengine and in this I want an object flying in the sky to drop bombs below. Currently I am using a timehandler to create both the flying object and the bombs. But its not working properly. The problems I am facing are:
1) Sometimes instead of a single bomb 2 or 3 bombs are dropped.
2) And the bomb objects are also not getting recycled. The code for recycling the object is getting called, but it doesn't seem to work.
I have noticed one thing i.e. suppose, initially I have one flying object that drops a bomb. When the bomb leaves the screen, the recycling code for bomb object gets called once. And after sometime as the flying object leaves the screen it also gets recycled. Now when another flying object is created and it drops the bomb, the code for recycling the bomb is getting called twice. Then for third flying object, the code for recycling the single bomb is getting called thrice and so on.
The code to add flying object is as follows
private void createDragonHandler() {
TimerHandler spriteTimerHandler;
float mEffectSpawnDelay = 10f;
spriteTimerHandler = new TimerHandler(mEffectSpawnDelay, true,
new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
addDragon();
}
});
getEngine().registerUpdateHandler(spriteTimerHandler);
}
public void addDragon() {
Dragon dragon = (Dragon) dragonSpritePool.obtainPoolItem();
if (dragon.getParent() != mainScene)
mainScene.attachChild(dragon);
}
public synchronized Dragon obtainPoolItem() {
dragon = super.obtainPoolItem();
Random rand = new Random();
final int x = (int) (CAMERA_WIDTH + resourceManager.dragonTextureRegion
.getWidth());
int minY = (int) resourceManager.dragonTextureRegion.getHeight();
int maxY = (int) (CAMERA_HEIGHT / 2 - resourceManager.dragonTextureRegion
.getHeight());
int rangeY = maxY - minY;
final int y = rand.nextInt(rangeY) + minY;
dragon.reset();
dragon.setVisible(true);
dragon.setIgnoreUpdate(false);
dragon.animate(150);
dragon.setPosition(x, y);
MoveXModifier mod = new MoveXModifier(15, dragon.getX(),
-dragon.getWidth());
float mEffectSpawnDelay = 5f;
TimerHandler spriteTimerHandler = new TimerHandler(mEffectSpawnDelay,
true, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
DragonFire dragonFire = BirdShoot.dragonFireSpritePool
.obtainPoolItem(dragon.getX(), dragon.getY());
BirdShoot.mainScene.attachChild(dragonFire);
}
});
dragon.registerEntityModifier(mod.deepCopy());
dragon.setNoHit(0);
PhysicsHandler mPhysicsHandler;
mPhysicsHandler = new PhysicsHandler(dragon);
dragon.setPhysicsHandler(mPhysicsHandler);
dragon.registerUpdateHandler(dragon.getmPhysicsHandler());
BirdShoot.engine.registerUpdateHandler(spriteTimerHandler);
return dragon;
}
`