实现游戏计时器计数毫秒

实现游戏计时器计数毫秒

本文介绍了CoronaSDK - 实现游戏计时器计数毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 timer.performWithDelay 来计算玩家完成关卡所需的时间.我希望它精确到 100 秒(因为游戏是多人游戏,我不希望有太多关系).

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).

这是我所做的:

local totaltime = 0

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

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

它导致每个秒"持续大约 4 秒.这是不切实际还是有什么地方有缺陷?

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

推荐答案

timer.preformWithDelay 的时间延迟小于帧之间的时间时,计时器将等待直到进入下一帧调用函数.

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.

这意味着,如果您的游戏以 30 或 60 fps 的速度运行,则帧毫秒"大约为 16 或 33 毫秒.因此,您可以放置​​的最小延迟是帧之间的延迟.

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.

在您的情况下,您希望每 1/100 秒或 10 毫秒设置一次计时器.这意味着,由于您的帧很可能是 16 毫秒(60 帧/秒),因此每记录 10 毫秒,您实际上都在等待额外的 6 毫秒.

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.

现在,如果您以 100 FPS 运行并因此达到所说的 10 毫秒,您就可以解决这个问题,但这是不推荐的.

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

AlanPlantPot 在 coronaLabs:

AlanPlantPot provided the answer for following solution on coronaLabs:

我会改用 enterFrame 函数.您的计时器不会在一个毫秒内上升(无论每帧经过多少毫秒,它都会增加),但无论如何没有人能够读得那么快.

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 )

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

这篇关于CoronaSDK - 实现游戏计时器计数毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!