How can I do something every second? [LibGDX]

岁酱吖の 提交于 2019-11-30 07:18:28

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!