I’m trying to lerp the alpha channel of a sprite renderer but it isn’t lerping, it just changes the alpha value so it instantly disappears instead of fading, I’ve searched everywhere but I can’t find a solution, here’s my code, please help.
(c#)
using UnityEngine;
using System.Collections;
public class MagicWalk : MonoBehaviour
{
Color fullAlpha = new Color (1f, 1f, 1f, 1f);
Color emptyAlpha = new Color (1f, 1f, 1f, -1f);
float speed;
SpriteRenderer magicCircle;
ParticleSystem magicPar;
void Awake ()
{
magicCircle = GetComponent<SpriteRenderer> ();
magicPar = GetComponentInChildren<ParticleSystem> ();
}
void Update ()
{
float h = Input.GetAxis("Horizontal");
speed = Mathf.Abs(h);
if (speed <= 0)
{
magicCircle.color = Color.Lerp (fullAlpha, emptyAlpha, 0.5f);
magicPar.enableEmission = false;
}
else if (speed > 0)
{
magicCircle.color = fullAlpha;
magicPar.enableEmission = true;
}
}
}
Lerp basically is that you have 2 values, Value A and value B. In the third parameter you specify the time. This value should be a value between 0 and 1.
A timeValue of 0 means value A will be reurned. A timeValue of 1 means value B will be returned. A timeValue of 0.5 means a value halfway in between value A and B is returned.
So in your current setup, sinse fullAlpha and emptyAlpha are constant, you will always return the same value (A value between [1,1,1,1] and [1,1,1,-1]).
There are 2 ways of making this work.
1:
float smooth = 1f; // Increase this for higher speed
magicCircle.color = Color.Lerp(magicCircle.color, emptyAlpha, Time.deltaTime * smooth);
Also, see this tutorial, stating at 4:20 for the Color.
R,G,B, and A color components range from 0 to 1. So:
Color emptyAlpha = new Color (1f, 1f, 1f, -1f);
should be:
Color emptyAlpha = new Color (1f, 1f, 1f, 0);
Your second problem is a logic problem (well, depends on what you’re trying to do). Your current code says, “if the speed is less than or equal to zero, pick a colour that’s halfway inbetween fullAlpha and emptyAlpha” - is that really what you meant? There’s no “fading” as such.