Reputation:
I am trying to create a smooth function to interpolate a number to zero. Problem is, it isn't working. In this case, if I increase a number by 0.01 a specified number of times, I want to decrease that number by 0.02 until it is zero. Here is my function.
float ReduceSpeed(float x)
{
if (x != 0f)
{
if (x % 0.02f != 0 && x > 0)
{
x = x - 0.01f;
} else if (x % 0.02f != 0 && x < 0)
{
x = x + 0.01f;
}
else
{
if (x > 0f)
{
x = x - 0.02f;
}
else
{
x = x + 0.02f;
}
}
}
return x;
}
I want to use this to create a kind of sliding motion in unity.
Upvotes: 0
Views: 54
Reputation: 13674
The problem most likely lies in the line
if (x != 0f)
x
is very likely to not be exactly zero due to rounding errors, since 0.01 and 0.02 are periodic numbers in base 2. You should choose a small value (epsilon) that you would compare the absolute value of x
against, e.g.
if (Math.Abs(x) < 1E-10)
Upvotes: 2