CoronaSDK - Implementing game timer counting milliseconds

前端 未结 1 1549
小鲜肉
小鲜肉 2021-01-28 12:57

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 mu

相关标签:
1条回答
  • 2021-01-28 13:10

    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
    
    0 讨论(0)
提交回复
热议问题