I watched and read many tutorials.
First, I learned about thread, then after awhile here comes Timer.
Which is which? and why?
I watched and read many tutorials.
First, I learned about thread, then after awhile here comes Timer.
Which is which? and why?
Using thread.sleep puts the entire logic of that thread on hold.
For instance most libaries run 1 thread and it usually holds the openGL context, which means if you use thread.sleep(), your entire game will lock up and nothing will update. You simply freeze the program.
A timer runs independently is usually timed using the computers system time or the delta time of your game (time since last frame)
For example:
float maxTime = 3 // 3 Secomds
float currentTime;
// This runs constantly, read more about game loops but it runs xx amount of times per second
public void gameLoop(float delta){
// If you can do the thing, do it
if(canDoThing)
doThingForSetTime(delta);
}
// The thing you want to do
private void doThingForSetTime(float delta) {
// Checks if the current time is less or equal to the maxtime
if (currentTime <= maxTime) {
// Adds the delta time onto the current time, eventually bringing it up to or past the maxtime
currentTime += delta;
} else {
// Then this kicks in and sets the boolean to false, making sure the game loop can now not call the method
canDoThing = false;
}
}
// The method to start the timer
public void startTimer(){
// Set the current time to zero
currentTime = 0;
// Tell the logic it can now do the thing
canDoThing = true;
}
So all you need to do is call the startTimer method outside of the game loop, say when an event triggers such as an enemy dieing, amybe you want to remove the dead sprite after xx amount of seconds, or maybe a bullet can only fly for 10 seconds and then needs to be removed.
You can make it more flexible by specifying times in the arguements like so:
// The method to start the timer
public void startTimer(float maxTime){
// Set the current time to zero
this.maxTime = maxTime;
currentTime = 0;
// Tell the logic it can now do the thing
canDoThing = true;
}