CoronaSDK - Implementing game timer counting milliseconds

两盒软妹~` 提交于 2019-12-04 06:25:46

问题


I am using timer.performWithDelay to time how long it takes a player to complete a level. I want it to measure down to the 100th of a second (because the game is multiplayer, and I don't want there to be too many ties).

Here is what I did:

local totaltime = 0

local function counter()
    totaltime = totaltime + 0.01
    print(totaltime)
end

timer1 = timer.performWithDelay( 10, counter, 0)

It results in each "second" lasting about 4 seconds. Is this just not practical or is there a flaw somewhere?


回答1:


When timer.preformWithDelay is given a time delay smaller then the time between your frames the timer will wait until the next frame is entered to call the function.

That means if you have a game running at 30 or 60 fps, you would have a 'frame ms' of about 16 or 33ms. So the minimum delay you can put is the delay between your frames.

In your case you want to set your timer every 1/100th of a second, or with 10ms. This means, since your frame is most likely 16ms (60fps), that every logged 10ms you are actually waiting an addional 6ms.

Now you could solve this if you ran with 100 FPS and thus achieved said 10 ms, but this is NOT recommendable.

AlanPlantPot provided the answer for following solution on coronaLabs:

I would use the enterFrame function instead. Your timer won't go up in single milliseconds (it will increase by however many ms have passed in each frame), but nobody would be able to read that fast anyway.

local prevFrameTime, currentFrameTime --both nil
local deltaFrameTime = 0
local totalTime = 0

local txt_counter = display.newText( totalTime, 0, 0, native.systemFont, 50 )
txt_counter.x = 150
txt_counter.y = 288
txt_counter:setTextColor( 255, 255, 255 )
group:insert( txt_counter )

and

local function enterFrame(e)
     local currentFrameTime = system.getTimer() 

    --if this is still nil, then it is the first frame 
    --so no need to perform calculation 
    if prevFrameTime then 
        --calculate how many milliseconds since last frame 
        deltaFrameTime = currentFrameTime - prevFrameTime
     end 
    prevFrameTime = currentFrameTime 
    --this is the total time in milliseconds 
    totalTime = totalTime + deltaFrameTime 

    --multiply by 0.001 to get time in seconds 
    txt_counter.text = totalTime * 0.001 
end


来源:https://stackoverflow.com/questions/24477016/coronasdk-implementing-game-timer-counting-milliseconds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!