开发者

Frame independent time in Lua?

I'm using Love2D to create a small game for my friends and I but, I'm having a problem: I want to calculate elapsed time, independent from the framerate. I'm tryi开发者_如何学Pythonng this but slight error adds up and eventually a 'second' passes in a 1/100th of a second.

local last_time = os.time()

function timeofday_update()
    world_time = world_time + os.time() - last_time
end


Why not mark the time at the beginning of the program, or beginning of whenever (starting_time = os.time()), and then 'current elapsed time' is just os.time() - starting_time. No accumulation necessary...


function make_stopwatch ()
    local start = 0
    local finish = 0
    local function sw (cmd)
        if cmd == "start" then
            start = os.time()
            return 0
        end
        if cmd == "lap" then
            return os.difftime(os.time(), start)
        end
        if cmd == "stop" then
            finish = os.time()
        end
        return os.difftime(finish, start)
    end
    return sw 
end

Demo:

> sw = make_stopwatch()
> =sw("start")
0
> =sw("lap")
16
> =sw "lap"
22
> =sw "lap"
28
> =sw "stop"
42
> = sw()
42
> = sw()
42
> = sw "start"
0
> = sw "lap"
8
> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜