You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Love2d实现倒计时与秒表功能计时不准问题求助

Love2d 倒计时/秒表计时不准问题解决方案

你遇到的计时偏快问题核心有两个:

  1. 直接累加/累减dt的方式会累积帧时间的误差,尤其是帧率波动、掉帧的场景下,误差会越来越明显
  2. 之前使用love.timer.getTime()如果还是采用累加逻辑,一样会有误差累积问题,正确用法是计算两个时间戳的差值做实时计算,不要累积计数

基于时间戳的倒计时实现

function love.load()
   -- 倒计时总时长,单位秒
   local countDownDuration = 3
   -- 记录倒计时开始的时间戳
   countDownStart = love.timer.getTime()
   countDownEnd = countDownStart + countDownDuration
   printMsg = false
end

function love.update(dt)
   local now = love.timer.getTime()
   if now < countDownEnd then
      -- 剩余时间可以实时算,不需要自己维护变量增减
      local remainTime = countDownEnd - now
      -- 这里可以加 remainTime 的业务逻辑,比如显示剩余时间
   else
      printMsg = true
   end
end

function love.draw()
   if printMsg then
      love.graphics.print('time over')
   end
end

基于时间戳的秒表实现

function love.load()
   timer = 0
   lives = 3
   -- 秒表开始的时间戳,初始设为nil表示未启动
   stopWatchStart = nil
   printMsg = false
end

function love.update(dt)
   if lives <= 0 and not stopWatchStart then
      -- 生命值耗尽时才记录秒表启动时间
      stopWatchStart = love.timer.getTime()
   elseif lives > 0 then
      printMsg = true
   end

   -- 秒表启动后实时计算已过时间,不需要累加dt
   if stopWatchStart then
      timer = love.timer.getTime() - stopWatchStart
   end
end

function love.draw()
   if printMsg and stopWatchStart then
      -- 可以用math.floor保留整数秒,避免小数跳变
      love.graphics.print('you have survived for '..math.floor(timer)..' seconds')
   end
end

function love.mousepressed(x, y, button)
   if button == 1 then
      lives = lives - 1
   end
end

额外优化建议

  • 如果需要做暂停功能,只需要额外记录暂停时刻的时间戳,恢复的时候把启动时间加上暂停的总时长即可
  • 显示时间时建议用math.floor或者字符串格式化保留固定小数位,避免数值频繁跳变影响观感
  • 若有固定帧率需求,可以在love.conf里开启vsync或者调用love.timer.setFPS()限制帧率,进一步降低帧波动影响

内容的提问来源于stack exchange,提问作者user16999379

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:15:03