Sven
Sven

Reputation: 11

My loop is looping more than it's supposed to

The script is supposed to gradually increase a glowing effect by decreasing transparency. Once the object is no longer touched, then it should gradually lose the glow until it's no longer glowing, by increasing transparency back to 1.

As I have it print the numeric values as it runs, I see that the values exceed 1 and seem to count at higher intervals than the .01 that is set in the loop. It doesn't work gradually - it cuts out or on abruptly as it runs through the loop.

I can't figure out why it's exceeding 1 or how to keep it as a gradual increase, even when the touching ends before reaching 100 iterations of the loop.

Here's the script:

local glow = script.Parent.orb
glow1 = 1

-- turn on when touched

glow.Touched:connect(function(obj)

    if obj.Parent:FindFirstChild("Humanoid") then
        for i = 0, 1, .01 do

            glow1 = glow1 - .01
            glow.ParticleEmitter.Transparency = NumberSequence.new(glow1)
            wait(.1)
            print(glow1)

        end
    glow1=0
    end
end)


-- turn off when no longer touched

glow.TouchEnded:connect(function(obj)

    wait(3)
    if obj.Parent:FindFirstChild("Humanoid") then
        for i = 0, 1, .01 do

            glow1 = glow1 + .01
            glow.ParticleEmitter.Transparency = NumberSequence.new(glow1)
            wait(.1)
            print(glow1)

        end
    end
end)

Upvotes: 1

Views: 150

Answers (2)

Null_Cat
Null_Cat

Reputation: 11

The Touched event could possibly be firing several times.

You can read more about it and how to fix it here.

Upvotes: 1

cyclaminist
cyclaminist

Reputation: 1817

At the end of the loop that counts up, glow1 is greater than 0 because 0.01 can't be exactly represented as a float. Its value is actually 0.01000000000000000020816681711721685132943093776702880859375 on my computer. That is the closest approximation in base 2, I guess. (Try print(('%.99f'):format(0.01)) to see the exact value on your machine.) So that multiplied by 100 is greater than 1.

There are other posters who are much better at math in Lua than I am, but as csaar might be suggesting, you could use a repeat until loop to make sure glow1 doesn't cross the boundary value (glow1 = 0.01 repeat --[[ do something here ]] glow1 = glow1 + .01 until glow1 > 1), or you could count and divide (for i = 1, 100 do glow1 = i / 100 --[[ do something here ]] end). Not sure which is better.

Upvotes: 3

Related Questions