9

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

CodingNub
  • 303
  • 1
  • 5
  • 17
  • How about http://stackoverflow.com/questions/12908412/print-hello-world-every-x-seconds? – snrlx Feb 14 '14 at 13:54
  • Use AsyncTask, Threads or Services if you wanna get the best of Android. But if you just want to print out "hello mario" or something else, google more. – Bedir Yilmaz Feb 14 '14 at 13:57

3 Answers3

26

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.

Robert P
  • 9,398
  • 10
  • 58
  • 100
10

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.

timeshift117
  • 1,720
  • 2
  • 18
  • 21
  • 3
    There is also an alternative without time by sum up the delta time till it is above 1000 and than execute the method, and resett the timer. (Do this inside of the render or act of an actor) – bemeyer Feb 14 '14 at 14:42
7

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 :)

lxknvlk
  • 2,744
  • 1
  • 27
  • 32