I want to create efficienty timer in LibGDX framework, that will count the time left for my character. The doSmth()
method should be called as many times as some flag is set to true. I know that the third parametr of Timer
is that, how many times should it trigger. For now one Im calling the method recursive, but I dont think it is the efficient way.
public void updateTimer(){
new Timer().scheduleTask(new Timer.Task() {
@Override
public void run() {
doSmth();
updateTimer();
}
},1);
}
The com.badlogic.gdx.utils.Timer executes tasks in the future on the main loop thread,even if your game is in a pause screen, a menu or in another state, you can simply control time in the render method by adding delta time.
To keep organized i personally have an array on my main game class that holds all my timed events and process everything on the render cycle. In your case you can put some control variables as you wish.
my implementation example:
// MainGame.java
// TimedEventEnum.java
//CountMoneyTimedEvent.java
//Timer.java
// TimedEvent.java
It would be more accurate to use a repeat count. Your method will introduce a bit of error each time the task is run, because the task is run on the GL thread, so it will occur just slightly after one second, but you are repeating it one second after that. So with each repeat you are slightly further behind.
And when you need to stop it: