greyBow
greyBow

Reputation: 1348

Lerping between two colors

I'm trying to transition between two colors, black to blue over a 1 second period but I can't seem to get it right. Currently when I click the button the color stays black and never transitions to blue. What do I need to fix? Thank you!

private Color startColor = Color.black;
        private Color endColor = new Color(0.0f, 0.71f, 1.0f, 1.0f);
        private float duration = 1.0F;

        void OnButtonClick ()
        {
            AppData.SelectedPageConfig = Page ;
            AnalyticsWrapper.CustomEvent ("SelectPicture", new Dictionary<string, object> {
                { "PictureName", Page.name }        
            }) ;

            StartCoroutine(DoChangeColor());
            StartCoroutine(DoChangeSceneDelay());
        }

        IEnumerator DoChangeColor()
        {
            float lerp = Mathf.PingPong(Time.deltaTime, duration) / duration;

            transform.Find("Creature Color Crop").transform.Find("Creature Image").GetComponent<Image>().color = Color.Lerp(startColor, endColor, lerp);

            yield return new WaitForEndOfFrame();
        }

        IEnumerator DoChangeSceneDelay()
        {
            yield return new WaitForSeconds(2);
            SceneManager.LoadScene("ColoringBook_ColoringScreen");
        }

Upvotes: 0

Views: 4399

Answers (1)

Programmer
Programmer

Reputation: 125275

Just like rotating or moving GameObjecss over time, The XXXLerp functions still function the-same way. It's worth reading that to understand how lerp works. The only thing to change there is Quaternion.Lerp to Color.Lerp.

bool changingColor = false;

IEnumerator lerpColor(Image targetImage, Color fromColor, Color toColor, float duration)
{
    if (changingColor)
    {
        yield break;
    }
    changingColor = true;
    float counter = 0;

    while (counter < duration)
    {
        counter += Time.deltaTime;

        float colorTime = counter / duration;
        Debug.Log(colorTime);

        //Change color
        targetImage.color = Color.Lerp(fromColor, toColor, counter / duration);
        //Wait for a frame
        yield return null;
    }
    changingColor = false;
}

Usage:

Image imageToLerp;

void Start()
{
    imageToLerp = transform.Find("Creature Color Crop").transform.Find("Creature Image").GetComponent<Image>();
    StartCoroutine(lerpColor(imageToLerp, Color.black, Color.blue, 1f));
}

Upvotes: 3

Related Questions