[Libgdx] Actions after a certain time elapsed

How to do the following with the least code possible?

-> After holding a certain key down for one second, do stuff

Now of course you can create a variable, increment that variable by delta time, and if that variable > 1, then do stuff, like


int ticks = 0;

public void foo(float delta) {
    if(keyDown) 
        ticks += delta;
        
        if(ticks > 1) doStuff();
    }
}

But I find that code clunky and adds variables to the class that I don’t really like.

Is there a more elegant way of doing it? (And btw I’m using kotlin language so don’t be afraid to post the possibilities in that language)

One possible solution could be having a singleton instance of input manager, which would allow to register the events with a stopwatch. On specific key down you start the stopwatch, on the key up, you reset the stopwatch for that key. Whenever you need to check the elapsed time, you access the stopwatch by key (or event) type.

If you’re using a Stage, I think you can use the class Actions.


float numberOfSecondsToWait = 2.f //or any other number

Actions.delay(numberOfSecondsToWait, Actions.run(new Runnable({
       
       @Override
       run(){

              //your code here

       }

}));

But if your Action is really an Action, so you just need to call there:

Actions.delay(numberOfSecondsToWait, Actions.yourAction());