For some reason the transparency doesn't change? Or doesn't even start?
function a() for i=0,1, .1 do wait(0.1) script.Parent.Transparency=i if i==1 then b() end end end function b() for j=1,0, -.1 do wait(0.1) script.Parent.Transparency=j if j==0 then a() end end end
I tried putting a() at the beginning but it hasnt read the code under it so i has no idea whats happening and so it dosnt do anything, i tried the bottom but it only fades invisible but not visible after? Help!
(TL;DR section at bottom)
The problem with floats
The problem here is actually not intuitive. You are using a for loop with floating point numbers. You might not know this, but it is impossible to precisely write every rational number in machine code. This site explains it nicely:
docs.python.org - floating point
So what is actually happening in your code is this:
You start with i
with value of 0
.
You do some code and increment i
by 0.1
.
But 0.1
cannot be precisely written in binary with final number of decimals.
Let's say we have precision of 64
bits. Converting 0.1
to binary gives us this:
0.0001100110011001100110011001100110011001100110011001100110011001
Now, of course, since we have limited storage capacity, we had to cut out all other digits, and therefore, the total precision. Converting this binary number back to decimal gives us this result:
0.0999999999999999999674739348254348669797764159739017486572265625
While this is really close to 0.1
, it isn't actually exactly 0.1
.
This happens with all the increments, 0.2
, 0.3
, all down to 0.9
.
Counter-intuitively, 0.9 + 0.1
is not equal to 1
when dealing with floating point numbers (unless the value is truncated and therefore rounded to correct value).
TL;DR: How to fix it
There are many methods to avoid this, I will name a few.
First method: rounding
First one that comes to mind is rounding the number.
To round a number, you could use math.floor
. But that function returns only smaller values, so 3.7
will not be rounded to 4
, but floored to 3
. This is not what we want.
We can avoid this by adding 0.5
to the number first, which will turn flooring to rounding.
if math.floor(i + 0.5) == 1 then -- code end
Second method: avoiding fractions
Another method you can use, is to use numbers that do not have a fractional value.
for i = 0, 10, 1 do -- We go from 0 to 10 wait(0.1) script.Parent.Transparency = i / 10 -- Notice that i is divided by 10, so it is correct value, from 0 to 1 if i == 10 then b() end end
Hope this helped.