简体   繁体   中英

Unity sprite fade in and out speed

I am trying to loop a fade-in and fade-out of a sprite in unity. I am new to Unity and C#.

My current code:

public float minimum = 0.0f;
public float maximum = 1f;
public float duration = 50.0f;

public bool faded = false;

private float startTime;
public SpriteRenderer sprite;

void Start () {
    startTime = Time.time;
}

void Update () {
    float t = (Time.time - startTime) / duration;

    if (faded) {
        sprite.color = new Color(1f, 1f, 1f, Mathf.SmoothStep(minimum, maximum, t));
        if (t > 1f) {
            faded = false;
            startTime = Time.time;
        }
    } else {
        sprite.color = new Color(1f, 1f, 1f, Mathf.SmoothStep(maximum, minimum, t));
        if (t > 1f) {
            faded = true;
            startTime = Time.time;
        }
    }
}

This works but it is too slow, I wish to make the fade in faster and the fade out a bit slower than the fade in. Something of the effect of a heartbeat. How do I update my code for that?

Also, is there a better approach to this? I think i'll get a memory leak with the too much NEW on the Update() .

As for what Andrew has given, I tried to debug his code:

    } else {
        sprite.color = new Color(1f, 1f, 1f, Mathf.Lerp(sprite.color.a, minimum, step));
        print (Mathf.Abs(sprite.color.a - minimum));
        print (threshold);

Shows me:

 2.206551E-20 // Mathf.Abs()?
 1.401298E-45 // threshold?

Dont worry about the new in the Update() , because Color is a value type, and C# is good at handling garbage collection

public float minimum = 0.0f;
public float maximum = 1f;
public float speed = 5.0f;
public float threshold = float.Epsilon;

public bool faded = false;

public SpriteRenderer sprite;

void Update () {
    float step = speed * Time.deltaTime;

    if (faded) {
        sprite.color = new Color(1f, 1f, 1f, Mathf.Lerp(sprite.color.a, maximum, step));
        if (Mathf.Abs(maximum - sprite.color.a) <= threshold)
            faded = false;

    } else {
        sprite.color = new Color(1f, 1f, 1f, Mathf.Lerp(sprite.color.a, minimum, step));
        if (Mathf.Abs(sprite.color.a - minimum) <= threshold)
            faded = true;
    }
}

Also, if all you care about is a fade in-out effect, all you need is a single line:

public float max = 1f;
public float speed = 5.0f;

public SpriteRenderer sprite;

void Update () {
    sprite.color = new Color(1f, 1f, 1f, Mathf.PingPong(Time.time * speed, max));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM