【问题标题】:Simple counting with a small delay [lua, LÖVE]带有小延迟的简单计数 [lua, LÖVE]
【发布时间】:2012-05-17 07:36:54
【问题描述】:

我是 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】:

    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 以确保我得到一个整数。

    【讨论】:

    • 这是正确的做法:更新更改状态,绘制根据该状态显示视觉内容。
    猜你喜欢
    • 1970-01-01
    • 2017-03-20
    • 2013-01-01
    • 1970-01-01
    • 2012-02-11
    • 2012-02-06
    • 2011-07-06
    • 1970-01-01
    • 2015-12-08
    相关资源
    最近更新 更多