How do I make a timer that times how long the player is playing the level of a game. I think you have to start timer and then I want the time to be saved to a variable. Thanks for help! [import]uid: 54001 topic_id: 9562 reply_id: 309562[/import]
Hi,
A good way to do this is to keep track of time using os.time…
Store that to a variable…and then use an “enterFrame” event listener that increments the seconds spent in the level.
Sure, you can use the timer functions…but I would be careful about it…since it was not completely stable the last time I used it.
So…use the “enterFrame” event listener…
You can do something like this in your code…
local startTime
-- Bonus code to format the time...makes the time elapsed
-- look better to the player
function formatTime(timeInSeconds)
local hoursLeft = math.floor(timeInSeconds / 3600)
local minutesLeft = math.floor((timeInSeconds - hoursLeft\*3600)/60)
local secondsLeft = (timeInSeconds - hoursLeft\*3600 - minutesLeft\*60)
local finalTimeString = ""
if(hoursLeft \> 0) then
finalTimeString = hoursLeft..[[h:]]
end
if(minutesLeft == 0 and hoursLeft == 0) then
else
finalTimeString = finalTimeString..minutesLeft..[[m:]]
end
finalTimeString = finalTimeString..secondsLeft..[[s]]
return finalTimeString
end
local function showTimer()
local currentTime = os.time()
local elapsedTime = currentTime - startTime
-- added bonus, you can also format the time with this
-- function :)
local elapsedTimeString
elapsedTimeString = formatTime(elapsedTime)
end
-- This is code you add to the initialization of the
-- screen/scene
function new()
.
.
.
startTime = os.time()
Runtime:addEventListener("enterFrame", showTimer)
.
.
.
end
***
Let me know if you run into any issues…enjoy
[import]uid: 12700 topic_id: 9562 reply_id: 34933[/import]