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

Roblox游戏「G4LC's Time Trials」计时功能故障求助

问题解决:Roblox计时器冗余数字与格式修正

问题说明

新作「G4LC's Time Trials」的计时功能故障:触发计时区域后前0.2秒显示正常,随后出现大量冗余数字,需将计时器格式改为「0:00」。

原故障代码

local PlayerGui = 
game:GetService("Players").LocalPlayer:WaitForChild("PlayerGui")

local Timer = PlayerGui:WaitForChild("TimerGui").Frame.Timer
local BoolVal = 
game:GetService("Players").LocalPlayer:WaitForChild("BoolStartEnd")
local Time = 0

while wait(0) do
if BoolVal.Value == true then
    Timer.TextColor3 = Color3.fromRGB(255, 255, 255)
    Timer.Visible = true
    Timer.Text = Time.."s"
    wait(0.1)
    Time = Time + 0.1
elseif BoolVal.Value == false then
    Timer.TextColor3 = Color3.fromRGB(0, 255, 0)
    Time = 0
    end
 end

问题根源

  1. 浮点数精度误差:直接累加0.1会触发二进制浮点数的精度缺陷,导致数值出现如0.30000000000000004这类冗余小数
  2. 格式未按需求处理:原代码仅简单拼接数值与s,未实现「分:秒」的目标格式

修正后的代码

local PlayerGui = game:GetService("Players").LocalPlayer:WaitForChild("PlayerGui")
local Timer = PlayerGui:WaitForChild("TimerGui").Frame.Timer
local BoolVal = game:GetService("Players").LocalPlayer:WaitForChild("BoolStartEnd")
local Time = 0

while task.wait() do -- 用task.wait()替代wait(0),性能更优
    if BoolVal.Value == true then
        Timer.TextColor3 = Color3.fromRGB(255, 255, 255)
        Timer.Visible = true
        
        -- 处理精度并格式化「0:00」格式
        local roundedTime = math.round(Time * 10) / 10 -- 保留一位小数,避免精度冗余
        local minutes = math.floor(roundedTime / 60)
        local seconds = math.floor(roundedTime % 60)
        
        -- 格式化秒数为两位,拼接成目标格式
        Timer.Text = string.format("%d:%02d", minutes, seconds)
        
        task.wait(0.1)
        Time = Time + 0.1
    else
        Timer.TextColor3 = Color3.fromRGB(0, 255, 0)
        Timer.Visible = false -- 停止计时时隐藏计时器,可选
        Time = 0
    end
end

关键改动说明

  • 用math.round(Time * 10) / 10修正浮点数精度,确保数值仅保留一位小数
  • 通过string.format("%d:%02d", minutes, seconds)实现「0:00」格式,%02d会自动给小于10的秒数补零
  • 替换wait(0)为task.wait(),Roblox官方推荐用task库提升性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:52:45