We'll need to create a couple of functions that activate the countdown and also stop at 0 seconds when the game is over:
myTimer()
:local myTimer = function()
counter
text object, display the time using numSeconds
. Print out numSeconds
to see the countdown in the terminal window:numSeconds = numSeconds - 1 counter.text = "Time: " .. tostring( numSeconds ) print(numSeconds)
if
statement for when the timer runs out or if all the stars are gone. Within the block, cancel the timer and call callGameOver()
to end the round. Close the myTimer()
function with end
:if numSeconds < 1 or stars.numChildren <= 0 then timer.cancel(timerInfo) panda:pause() restartTimer = timer.performWithDelay( 300, function() callGameOver(); end, 1 ) end end
myTimer()
function with a new local function called startTimer()
. This will start the countdown at the beginning of the game play:local startTimer = function() print("Start Timer") timerInfo = timer.performWithDelay( 1000, myTimer, 0 ) end
The main timer function is within myTimer()
. We count down the seconds using numSeconds = numSeconds – 1
. The seconds will update in the counter
display object. print(numSeconds)
will be updated in the terminal window to see how fast the countdown runs inside the code.
When time runs out or all the stars have been collected, an if
statement is created to check if any of the arguments are true. When any statement evaluates to true, the timer stops counting down, the panda animation pauses, and the callGameOver()
function is called. This will call the function to display the game over screen.
The timer initiates the countdown through local startTimer = function()
at a rate of 1,000 milliseconds, which is equivalent to 1 second.