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 A and B depending on C.

Math.Lerp(A, B, C);

If C varies from the beginning to the end, you can simulate an Fade In or Fade out transition, for example.

In the example below, I want to go from 1 (A) to 0 (B) (fade out transition) in 3 seconds.

The for loop will take 3 seconds to complete (Time.deltatime / 3) and C will be an incremental value from 0 to 1.

We can think as if it was an Slider controller: when C are at the left (0), the value is A, if you slide to the right (1) the value is Y.

SpriteRenderer sprite = GetComponent<SpriteRenderer>();
void Start()
    {
        StartCoroutine(fade1());
    }

    IEnumerator fade1()
    {
        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: