我是 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
定时器之所以会如此疯狂,是因为它是一个浮点十进制数。防止这种情况发生的一个简单方法是在显示数字时对其进行格式化。
所以尝试这样的事情:
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
-- format the time to be mm:ss.ms
local minutes = math.floor(Time / 60)
local seconds = Time - (minutes * 60)
-- string format pattern explanation :
-- %02d = an integer with a minimum width of 2 characters, padded with zeros
-- %05.2f = a floating point number with a minimum width of 5 characters, two decimal places, and padded with zeros
Timer.Text = string.format("%02d:%05.2f s", minutes, seconds)
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)