Hey all,
I’m new to Corona and coding in general, but after looking to implement a timer/stopwatch in my game, I’ve created something which I think looks and generally works well but…
Although the logic seems fine to me, the time keeping is not 100% accurate.
I’ve tested it running alongside a real stopwatch and over the course of a minute it seems to lag a few seconds behind.
Can you spot where my logic and/or code is wrong? Or, is there some particular reason why this would be?
On a separate note, I tried to find some example code for a timer like this everywhere and could not. I think it’s suits a great variety of apps and games - puzzle, racing, etc. So, if people think that this would be useful to others, I’m going to post it the ‘Share Your Code’ section - when it’s working correctly of course.
Anyway, here’s what I have so far:
[lua]local _W, _H = display.contentWidth, display.contentHeight
local seconds, minutes, tenthSeconds
– Create basic start button (text)
local startButtonText = display.newText( “Tap To Start”, 0, 0, native.systemFont, 24 )
startButtonText.x = _W / 2; startButtonText.y = (_H / 2) + 80
startButtonText:setTextColor( 255, 255, 255 )
– Create basic start/stop button
local timerCount = display.newText( “00:00:0”, 0, 0, native.systemFont, 48 )
timerCount.x = _W / 2; timerCount.y = (_H / 2) - 40
timerCount:setTextColor( 255, 255, 255 )
local function startTimer(e)
startButtonText:removeSelf()
startButtonText = nil
function timerCount:timer( event )
local count = event.count
tenthSeconds = math.floor(count % 10)
seconds = math.floor(count / 10 ); seconds = math.floor(seconds % 60)
minutes = math.floor(count / 600); minutes = math.floor(minutes % 60)
timeFormat = string.format("%02d:%02d:%01d", minutes, seconds, tenthSeconds)
self.text = timeFormat
if count >= 6000 then
timer.cancel( event.source ) – Cancel timer after 10 mins
end
end
timer.performWithDelay( 100, timerCount, 6000 ) – Call timerCount function every 1/10th second for 10 minutes
end
– Tap event listener for start button (text)
startButtonText:addEventListener(“tap”, startTimer)[/lua] [import]uid: 74503 topic_id: 14675 reply_id: 314675[/import]