How to change TimerHandler delay in AndEngine?

2019-02-07 14:57发布

问题:

I have this method i create that adds a sprite to my andengine scene every second.

 private void createSpriteSpawnTimeHandler(){
        TimerHandler spriteTimerHandler;
        float mEffectSpawnDelay = 1f;
        spriteTimerHandler = new TimerHandler(mEffectSpawnDelay,true,new ITimerCallback(){
        @Override
        public void onTimePassed(TimerHandler pTimerHandler) {
                addFace();
        }
        });
        getEngine().registerUpdateHandler(spriteTimerHandler);
}

What i want to do is, for example

if(x <= b){

 mEffectSpawnDelay = mEffectSpawnDely - .2f;
 }

The problem i am running into is that when the variable is changed. I cant figure out a way to update the TimeHandler letting it know to change the mEffectSpawnDelay variable.

Any suggestions?

回答1:

I have created this class just now for you. I think it should work, and you can change the interval between ticks as you wish. (Haven't tested it, so you might need to make some small fixes. But it looks fine IMO.)

Use it this way:

Timer timer = new Timer(interval, new Timer.ITimerCallback() {
    public void onTick() {
        //Your code to execute each interval.
    }
}
(Engine object here).registerUpdateHandler(timer);

If you ever want to change the interval, you should keep a reference to the timer. Anyways, to change interval use:

timer.setInterval(newInterval);


回答2:

Store the handler in an instance variable, and call its setTimerSeconds method when needed.



回答3:

Looking at the TimerHandler source file here: http://code.google.com/p/andengine/source/browse/src/org/anddev/andengine/entity/handler/timer/TimerHandler.java?r=30ba07312ed7d4636077b835ba15f772e3f30db7

You'll see that there isn't a method to update the interval. And the variable mTimerSeconds is also final.

I would implement my own IUpdateHandler class and add a non-final mTimerSeconds and a method to update it.

You can copy the existing TimerHandler and then make the changes accordingly.



回答4:

Override onCreateEngine method with new FixedStepEngine

@Override
public Engine onCreateEngine(EngineOptions pEngineOptions) {

    return new FixedStepEngine(pEngineOptions, 30);
}