Unity精灵渐入淡出

时间:2015-09-08 13:29:20

标签: c# unity3d

我试图以团结的形式循环淡化和淡出精灵。我是Unity和C#的新手。

我目前的代码:

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;
        }
    }
}

这有效但速度太慢,我想让淡入淡出更慢,淡出的速度比淡入淡出慢一些。心跳的效果。如何更新我的代码?

另外,有更好的方法吗?我想NEW Update()上的 } else { sprite.color = new Color(1f, 1f, 1f, Mathf.Lerp(sprite.color.a, minimum, step)); print (Mathf.Abs(sprite.color.a - minimum)); print (threshold); 太多会导致内存泄漏。

至于Andrew给出的内容,我试图调试他的代码:

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

告诉我:

AVPlayer

1 个答案:

答案 0 :(得分:1)

不要担心new中的Update(),因为Color是值类型,C#擅长处理垃圾回收

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;
    }
}

此外,如果你关心的只是淡入效果,你只需要一行:

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));
}