简单计数,延迟很小[lua,LÖVE]

问题描述 投票:1回答:1

我是lua和LÖVE的新手。

我试图用一个小延迟对数字进行简单的计数,这样用户就可以看到计数发生了(而不是简单地计算代码,然后显示完成的计数)

我有以下代码:

function love.draw()
    love.graphics.print("Welcome again to a simple counting sheep excercise.", 50, 50)

    i = 20
    ypos = 70

    while i > 0 do

        love.graphics.print("Number: " .. i .. ".", 50, ypos)
        love.timer.sleep(1)
        i = i - 1
        ypos = ypos + 12


    end

end

但是当我运行它时,它只会挂起约20秒然后显示完成的计数。如何在每次迭代之间暂停?我怀疑问题是draw函数被调用一次,所以它在显示之前完成了它的所有工作。

lua love2d
1个回答
4
投票

love.draw()每秒被调用很多次,所以你不应该真正睡觉,因为它会导致整个应用程序挂起。

相反,使用love.update()根据当前时间(或基于时间增量)更新应用程序的状态。

例如,我会表达你想要做的事情如下:

function love.load()
   initTime = love.timer.getTime()
   displayString = true
end

function love.draw()
    love.graphics.print("Welcome again to a simple counting sheep excercise.", 50, 50)
    if displayString then
        love.graphics.print("Number: " .. currentNumber .. ".", 50, currentYpos)
    end
end

function love.update()
    local currentTime = love.timer.getTime()
    local timeDelta = math.floor(currentTime - initTime)
    currentNumber = 20 - timeDelta
    currentYpos = 70 + 12 * timeDelta
    if currentNumber < 0 then
        displayString = false
    end
end

首先我找到初始时间,然后根据与初始时间的时差来计算数字和位置。差异以秒为单位,这就是为什么我打电话给math.floor以确保我得到一个整数。

© www.soinside.com 2019 - 2024. All rights reserved.