Have a certain transparency based on distance?

Hi,

This is really simple but I just keep on confusing myself and I’m not sure why. My brain is just saying no right now.

What I want is that if my distance to a marker is 20m or less, then it’s alpha is 0.8. Then past that, up to a distance of 50, I want the transparency to lerp smoothly between 0.8 and 0.2. Is it inverselerp? I dont know!

float maxAlpha = 0.8f;
float minAlpha = 0.2f;
int minDistance = 20;
int maxDistance = 50;

if ( distance <= minDistance )
{
    col.a = maxAlpha;
}
else
{
    // Code here
}

Any help would be massively appreciated!

Two steps:

Step 1: calculate the “fraction” (third term of Lerp) from your near limit to far limit

float fraction = (distance - minDistance) / (maxDistance - minDistance);

Step 2: use the fraction with Mathf.Lerp() to tween between your alphas:

col.a = Mathf.Lerp( maxAlpha, minAlpha, fraction);

Lerp doesn’t care about its direction-ness: it’s happy to go up or down. The only thing it cares about is that third term’s position between 0.0 and 1.0f.

Same goes for Vector3.Lerp() coincidentally.

Also don’t be confused by the fact that some documentation actually calls that third term “alpha,” hence why I use ‘fraction’ in the code above. I think the current docs call it ‘t’ which is better.

Perfect, thank you so much. I was trying it myself and I was getting a percentage for the lerp, but I was getting the wrong percent.

Would you be able to explain why the fraction is done this way? float fraction = (distance - minDistance) / (maxDistance - minDistance);Don’t worry if not - I just like to understand why stuff happens but my maths honestly isn’t that great.

The algebraic thinking process I used to create that expression is “I want the output to be zero at min distance.”

Therefore I subtract minDistance from distance. (Could become negative, but just keep reading).

Then I think, “I want it to be 1.0 at maxDistance, BUT I have already subtracted minDistance from it.”

Therefore I must divide it by the span, which is maxDistance minus minDistance, which will make it 1.0 at maxDistance.

Finally I am making use of the fact that this particular Lerp implementation clips below 0.0 and above 1.0. Other lerp implementations may extrapolate the lerp beyond the endpoint boundaries, which sorta makes them more of a “linear rescale” function than a linear interpolation (lerp) function.

Hope that clarifies things a bit!

1 Like

Thank you very much!

Thanks Kurt, this will definitely help me in the future. :slight_smile:

1 Like