Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to make it fire when the i variable is 0.0 instead of 0.1?

Asked by 7 years ago
Edited 7 years ago

This is a LocalScript and the place is FE!

local remotes = game:GetService("ReplicatedStorage").Remotes

function round(x, dc)
    x = x * (10 ^ dc) -- dc is the number of decimal places... cuz math.floor or math.ceil cannot even do so...
    x = x + 0.5 - (x + 0.5) % 1
    x = x / (10 ^ dc)
    return x
end

function FormatTimeText(Number)
    local minutes = math.floor(Number/60)
    local seconds = round(Number % 60, 1)
    return string.format("%d:.1f", minutes, seconds)
end

local prepare = remotes:WaitForChild("Prepare")
prepare.OnClientEvent:Connect(function(mapName, creators, timeLimit)
    script.Parent.Text = FormatTimeText(timeLimit)
    script.Parent:TweenPosition(UDim2.new(0.375, 0, 0, 0), "In", "Linear", 0.5)
end)

local start = remotes:WaitForChild("GameStart")
start.OnClientEvent:Connect(function(TimeLimit)
    local plrGui = script.Parent.Parent.Parent
    local antiExplode = false

    for i = TimeLimit, 0, -0.1 do -- Problem here, maybe?
        if plrGui:FindFirstChild("WinLoseGui") then
            antiExplode = true
            break
        end
        script.Parent.Text = FormatTimeText(i)
        wait(0.1)
    end

    if antiExplode == false then
        print("Time's up!")
        remotes:WaitForChild("TimesUp"):FireServer()
    end
end)

local tweenDefault = remotes:WaitForChild("TweenDefault")
tweenDefault.OnClientEvent:Connect(function()
    script.Parent:TweenPosition(UDim2.new(0.375, 0, -1, 0), "In", "Linear", 0.5)
    script.Parent.Text = "0:00.0"
end)

The function will start when the start event fires (because it is the start of a run/race) I want it so when the time is 0:00.0 then the TimesUp event will fire. However, the event was fired when the timer hits 0:00.1. I don't know how to do it (plus, i think the problem is about the number in the variable i).

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago
Edited 7 years ago

This is because of floating point error.

If you do something like 60 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1 ... you get down to something like 0.099999999999416 rather than an even 0.1.

When you subtract the final 0.1, it's -5.8400506652845e-013, a negative number -- past 0 -- so Lua doesn't execute it for the last loop.


The easiest solution is to count down by whole numbers only. You can do that like this:

for i10 = 10*TimeLimit, 0, -1 do
    local i = i10 / 10

    ......
0
Ahh! I see. it is always good to know more about the Lua scripting language. Thanks! :) starlebVerse 685 — 7y
Ad

Answer this question