I’ve had a problem with Lerping logic for a while where I need to ‘reset’ the lerp back to 0. I can’t figure out a way of
I have this bit:
public void ObjectFade (int from, int to, float speed)
{
transLerp = Mathf.Lerp (from, to, Time.time / speed);
nonOccludeCollideRend.material.SetFloat ("_TransparencyMultiplier", transLerp);
}
It runs the first time once fine, but repeating it is baffling me at the moment.
I’ve tried to reset the time initialiser to 0 (i’ve replaced the initialiser with time.time here to save space, but it does pretty much the same).
This will go from one value to another (from, to), but running the routine again just steps from from<->to without lerping.
I’m about to look at it again, but I just thought I’d ask here, is there a simple way of doing it? Thanks
Well this seemed to work:
public float fadeIn, fadeOut;
...
public void ObjectFadeIn (int from, int to, float speed)
{
fadeIn += Time.deltaTime;
transLerp = Mathf.Lerp (from, to, fadeIn);
nonOccludeCollideRend.material.SetFloat ("_TransparencyMultiplier", transLerp);
fadeOut = 0;
}
public void ObjectFadeOut (int from, int to, float speed)
{
fadeOut += Time.deltaTime;
transLerp = Mathf.Lerp (from, to, fadeOut);
nonOccludeCollideRend.material.SetFloat ("_TransparencyMultiplier", transLerp);
fadeIn = 0;
}
Anytime I lerp anything over time, I use this pattern, in a coroutine:
IEnumerator LerpAcrossInterval( float interval)
{
float fraction = 0.0f;
float age = 0.0f;
do
{
fraction = age / interval;
age += Time.deltaTime;
// Apply Lerp here using 'fraction' as controller alpha, as
// fraction goes from 0.0 to 1.0 over time "interval"
// for example:
Vector3 position = Vector3.Lerp( startPosition, endPosition, fraction);
// or alternately:
float size = Mathf.Lerp( minSize, maxSize, fraction);
// or for color:
Color color = Color.Lerp( Color.red, Color.green, fraction);
yield return null;
} while( fraction < 1.0f);
}
This ensures:
- correct time interval
- first one is always lerped at 0.0 (so you get pure first value)
- last one is always lerped at 1.0 (so you get pure last value)
If you don’t ensure #3 above you can have weird things like 0.999 opaque or 0.001 translucent.
EDIT: I came back to add the yield return null;
because I forgot it the first time through.
Thanks Kurt, I’ll probably come back to that one. 