Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do something every second? [LibGDX]

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

like image 581
CodingNub Avatar asked Feb 14 '14 13:02

CodingNub


3 Answers

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();
}
  • check out the libgdx API : TimeUtils

For some reason my solution seemes more elegant to me that those offered here :)

like image 51
lxknvlk Avatar answered Nov 15 '22 00:11

lxknvlk


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.

like image 32
Robert P Avatar answered Nov 15 '22 00:11

Robert P


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.

like image 10
timeshift117 Avatar answered Nov 15 '22 02:11

timeshift117