31 de mai de 2017

Fade Out and Fade IN using Mathf.Lerp()

Lerp is a very interesting function because it changes a value between X and Y incrementing (or decrementing) by a W value. If W varies from de beginning to the end, you can simulate an Ease In and Out too.

In the example below, I want to go from 1 to 0 (fade effect) in 3 seconds.

The for loop will take 3 seconds to complete and X will be an incremental value from 0 to 1 for the Ease effect.

void Start()

    IEnumerator fade1()
        SpriteRenderer sprite = GetComponent<SpriteRenderer>();
        Color newColor;

        for (float x = 0f; x < 1f; x += Time.deltaTime / 3)
            newColor = new Color(1, 1, 1, Mathf.Lerp(1, 0, x));
            sprite.color = newColor;

            yield return null;


Nenhum comentário: