"Color.Lerp();" is not working as I wanted

“Color.Lerp();” is not working as I wanted, no matter what I did it didn’t work why? Does anyone have an idea? I would be very happy if you could help me

for example, I set the rabbitGroundTime variable to 180f, normally it should shift to the color I want with lerp in 180 seconds, but even though rabbitGroundTime is 180f, it turns to the color I want in 3 seconds, I can’t solve the problem, I accessed all the channels (r,g,b,a) in the myColor variable one by one and did “Mathf.Lerp();” but that didn’t work either? why?

 private void FootBurningOfRabbit()
 {
     if (RabbitGroundControl())
     {
         if (rabbitGroundTimeCount >= rabbitGroundTime)
         {
             rabbitGroundTimeCount = 0f;
             rabbitFreeze = true;
             isRabbitDeath = true;
             isRabbitDefinitelyDead = true;
         }
         else if (!isRabbitDeath)
         {
             Color myColor = myRenderer.color;
             currentlyRabbitHealth = Mathf.Lerp(rabbitMaxHealth, rabbitMinHealth, rabbitGroundTimeCount / rabbitGroundTime);
             myRenderer.color = Color.Lerp(myColor, deathColor, rabbitGroundTimeCount / rabbitGroundTime);
             ParticleSystem.EmissionModule emission = myParticleSystem.emission;
             emission.rateOverTime = new ParticleSystem.MinMaxCurve(100 - currentlyRabbitHealth);
             rabbitGroundTimeCount += Time.deltaTime;
         }
     }
 }

Well, you use Lerp the wrong way. You use the “current” value as start value of the lerp and you also increase the percentage to lerp between start and end. So you get a non linear increase. You need to store the start and end value and keep them constant in order to lerp linearly.

An alternative would be to use something like MoveTowards. However Color doesn’t have such a method. Though a Color value can be converted into a Vector4 and you could use Vector4.MoveTowards. With this method you would need to use the current value and the target value as well as the speed at which to move towards the target.

1 Like

Adding to this, what you likely want is a something to smoothly move from 0.0 to 1.0 in the 180 seconds.

You would use that value in the third argument of a call to Color.Lerp(); to go between two known colors.

This is an extremely common gamedev pattern: using a scalar parameter to control other non-scalar parameters.

And do not use a coroutine to smoothly move the value, unless you never want it to go back, or stop, or pause, or reverse.

Instead, try this approach:

Smoothing the change between any two particular values:

You have currentQuantity and desiredQuantity.

  • only set desiredQuantity
  • the code always moves currentQuantity towards desiredQuantity
  • read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

The code: SmoothMovement.cs · GitHub

2 Likes