TimerHandler in andengine spawing sprites at a interval
Question
I am using this TimerHandler in andEngine to spawn sprites at certain times..
mScene.registerUpdateHandler(new TimerHandler(0.02f, true, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
addSpriteTime1 += 2; // because timer update = 0.02 seconds
if (addSpriteTime1 == nextSprite1Time) {
addFace();
addSpriteTime1 = 0;
}
addSpriteTime2 += 2;
if (addSpriteTime2 == nextSprite2Time) {
addFace2();
addSpriteTime2 = 0;
}
addSpriteTime3 += 2;
if (addSpriteTime3 == nextSprite3Time) {
addFace3();
addSpriteTime3 = 0;
}
}
}));
Now i have int variables declared at class level..
private int nextSprite1Time = 100;// initial value, could be changed during game
private int nextSprite2Time = 100;
private int nextSprite3Time = 100;
I then have a method which allows me to change the speed or the nextSpriteTimes.
private void speed(int f, int g, int h){
this.nextSprite1Time = f;
this.nextSprite2Time = g;
this.nextSprite3Time = h;
Log.e("Time Changed", String.valueOf(this.nextSprite1Time+ "," + this.nextSprite2Time + ","+ this.nextSprite3Time));
}
The problem is when i try to change the speed for example..
speed(30, 50, 70);
It just stops all together and now sprites are added,
Does anyone see where i am going wrong with this or can do it differently?
Solution
First of all - Your log message in speed
method is not an error - why are you using Log.e
method? That's for errors... Use Log.d
(debug) or Log.i
(information) instead.
Back to your problem. I didn't understand exactly what you meant, but I do see a problem:
Lets say that nextSprite1Time = 100
and addSpriteTime1 = 70
. Up untill here, everything is fine, right? In five more onTimePassed
calls, a new sprite will be added.
But now you changed nextSprite1Time
to 60
. addSpriteTime1
is still 70
, and since it is larger than 60 it will never add a new sprite!
Solution: Use >=
instead of ==
, and don't zero the counters but decrease the value of nextSpriteTime
from them, for example, for sprite 1:
addSpriteTime1 += 2;
if(addSpriteTime1 >= nextSprite1Time) {
addFace();
addSpriteTime1 -= nextSprite1Time;
}