我是 Roblox 的一名小型开发者,我的新游戏“G4LC 的计时赛”需要帮助。计时器在前 0.2 秒内运行良好,但随后就变得疯狂。本质上,当我走进启动计时器的部分时,它确实启动了计时器,但突然出现了大约 9 个额外的数字,我想要的只是计时器布局像“0:00”,这里是链接 观看问题视频。
我把计时器放进去,我测试了一下,结果是这样的
没有其他问题,除了可能是在 TimerGUI 中。 TimerGUI 才是最重要的。这是代码:
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
计时器如此疯狂的原因是因为您的
Time
变量存储为浮点十进制数。他们因这样的事情而臭名昭著
0.1 + 0.2 = 0.30000000000001
--And
0.1 + 0.2 = 0.29999999999999
忽略此行为的一个简单方法是在显示数字时对其进行格式化。
所以尝试这样的事情:
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local PlayerGui = Players.LocalPlayer:WaitForChild("PlayerGui")
local Timer = PlayerGui.TimerGui.Frame.Timer
local BoolVal = Players.LocalPlayer.BoolStartEnd
local Time = 0.0 -- seconds
local function updateTimer(deltaTime)
Time += deltaTime
-- convert passed time to minutes and second
local minutes = math.floor(Time / 60)
local seconds = math.floor(Time - (minutes * 60))
-- format the time to be m:ss
Timer.Text = string.format("%d:%02d s", minutes, seconds)
-- string format pattern explanation :
-- %d = an integer
-- %02d = an integer with a minimum width of 2 characters, padded with zeros
end
local timerConnection
BoolVal.Changed:Connect(function(isTrue)
if isTrue then
-- update the color
Timer.TextColor3 = Color3.fromRGB(255, 255, 255)
Timer.Visible = true
-- start the timer!
timerConnection = RunService.Heartbeat:Connect(updateTimer)
else
-- update the color
Timer.TextColor3 = Color3.fromRGB(0, 255, 0)
-- reset and stop the timer
Time = 0
if timerConnection then
timerConnection:Disconnect()
timerConnection = nil
end
end
end)
我没有使用无限 while 循环,而是使用更适合 Roblox 的
RunService.Heartbeat
信号。每次游戏引擎更新世界时都会触发它,并且 deltaTime
参数是自上次更新以来经过的秒数。这样,计时器就不必浪费时间检查 BoolVal
是否为 true;如果 BoolVal
为 true,它将启动计时器,否则将完全停止计时器。