Lets say I want to make a loop or something that prints out, for example, "Mario" every second. How can I do this? Can't seem to find any good tutorials that teach this anywhere =P
I used the TimeUtils of libgdx to change my splashscreen after 1.5 seconds. The code was something like this:
initialize:
long startTime = 0;
in create method:
startTime = TimeUtils.nanoTime();
returns the current value of the system timer, in nanoseconds.
in update, or render method:
if (TimeUtils.timeSinceNanos(startTime) > 1000000000) {
// if time passed since the time you set startTime at is more than 1 second
//your code here
//also you can set the new startTime
//so this block will execute every one second
startTime = TimeUtils.nanoTime();
}
For some reason my solution seemes more elegant to me that those offered here :)
As @BennX said you can sum up the delta
time you have in your render method or get it by calling Gdx.graphics.getDeltaTime();
. If it is bigger then 1
(delta
is a float
, giving the seconds since the last frame has been drawn), you can execute your task. Instead of reseting your timer by using timer = 0;
you could decrement it by using timer -= 1
, so your tasks get executed more accurate. So if 1 task starts after 1.1 seconds
, cause of a really big delta
the next time it gets executed after arround 0.9
seconds.
If you don't like the delta
time solution you can use Libgdx timer, instead of java.util.Timer.
An example of it:
Timer.schedule(new Task(){
@Override
public void run() {
doWhatEverYouWant();
}
}
, delay // (delay)
, amtOfSec // (seconds)
);
This executes the doWhatEverYouWant()
method after a delay of delay
and then every seconds
seconds. You can also give it a 3rd parameter numberOfExecutions
, telling it how often the task should be executed. If you don't give that parameter the task is executed "forever", till it is canceled.
You can use java.util.Timer.
new Timer().scheduleAtFixedRate(task, after, interval);
task is the method you want to execute, after is the amount of time till the first execution and interval is the time between executions of aforementioned task.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With