https://kotlinlang.org logo
#korge
Title
# korge
r

Rishav Sharan

06/03/2020, 12:20 PM
I want to add a simple timer. Something like this
Copy code
var breakTime = 3
        var breakTimeText = text("Starting game in $breakTime seconds") {
            position(10, 500)
            addUpdater {
                Count down to 0 in 1 sec intervals
                update breakTime on each interval
                if 0, then call function breakOver

            }
        }
i want the counter to go down to zero and then call a function. any tips on how I can achieve that?
r

RezMike

06/03/2020, 12:31 PM
One of the ways:
Copy code
var breakTime = 3
val breakTimeText = text("Starting game in $breakTime seconds").position(10, 500)
launchImmediately {
	while (breakTime > 0) {
		println(breakTime)
		breakTimeText.text = "Starting game in $breakTime seconds"
		delay(1.seconds)
		breakTime--
	}
    callFunction()
}
r

Rishav Sharan

06/03/2020, 12:41 PM
Thanks!
Is there a variant which can work from within the addUpdater or at every tick? What I want to do is to check the current game state at every tick. If the state = something, then after n seconds update the state to something else. Trying this code within addUpdater throws
Suspension functions can be called only within coroutine body
r

RezMike

06/03/2020, 12:58 PM
You can get the same result with a simpler approach. When you change your state to 'something', you need to call a function that will start the count down.
So you won't need to add additional check that runs every tick. You just call the action right when the state is changed.
n

Nico

06/03/2020, 1:21 PM
The
it
in addUpdater has the timespan which passed since the last frame if that helps.