How can I do something every second? [LibGDX]

后端 未结 3 578
再見小時候
再見小時候 2020-12-30 11:53

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 a

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-30 12: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.

提交回复
热议问题