Search code examples
javaandroidlibgdx

Set a delay in libGDX


I have now tried to set up a delay in libGDX in three different ways.

First I tried to use a Timer, but if I restart the activity, the timer won't start again. This is a known issue when using GestureDetector: https://github.com/libgdx/libgdx/issues/2274

Then I tried setting up a timer using Gdx.graphics.getDeltaTime in my render method, but this doesn't work for me as I have set it to non-continous rendering. Described in answer #2 set a delay in libgdx game

Finally I tried using a while loop and System.getCurrentTimeMilliseconds, however this prevented the application from recognizing a tap while the while loop was looping.

I have also heard of DelayAction, but how does one implement that into the code? https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/actions/DelayAction.html

Is there another way of setting a delay? How do one implement DelayAction? Or how does one fix the Timer bug in libGDX?


Solution

  • Inspired by Barodapride's comment, I found a solution where I make a new thread, and put the while loop here. This code will wait for 1000 ms, and then run foo() on the main thread.

    new Thread(new Runnable() {
                @Override
                public void run() {
                    long time = System.currentTimeMillis();
                    while (System.currentTimeMillis() < time + 1000){}
                    Gdx.app.postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            foo();
                        }
                    });
                }
            }).start();