随时间来回改变光强度

时间:2018-07-27 14:26:26

标签: c# unity3d light

如何在2秒后将光强度值从3.08更改回1.0。我在我的代码中有注释以获取其他信息

public class Point_LightG : MonoBehaviour {

    public Light point_light;
    float timer;

    // Use this for initialization
    void Start () {
        point_light = GetComponent<Light>();
    }

    // Update is called once per frame
    void Update () {
        timer -= Time.deltaTime;
        lights();
    }

    public void lights()
    {
        if (timer <= 0)
        {
            point_light.intensity = Mathf.Lerp(1.0f, 3.08f, Time.time);
            timer = 2f;
        }

        // so after my light intensity reach 3.08 I need it to gradually change back to 1.0 after 2 seconds.
    }
}

1 个答案:

答案 0 :(得分:1)

要在两个值之间进行约束,只需将Mathf.PingPongMathf.Lerp一起使用,并提供约束发生的速度。

public Light point_light;
public float speed = 0.36f;

float intensity1 = 3.08f;
float intensity2 = 1.0f;


void Start()
{
    point_light = GetComponent<Light>();
}

void Update()
{
    //PingPong between 0 and 1
    float time = Mathf.PingPong(Time.time * speed, 1);
    point_light.intensity = Mathf.Lerp(intensity1, intensity2, time);
}

如果您希望使用持续时间而不是 speed 变量来控制光强度,那么最好使用协程函数和{{1 }}带有一个简单的计时器。然后可以在x秒内完成lerp。

Mathf.Lerp

用法

IEnumerator LerpLightRepeat()
{
    while (true)
    {
        //Lerp to intensity1
        yield return LerpLight(point_light, intensity1, 2f);
        //Lerp to intensity2
        yield return LerpLight(point_light, intensity2, 2f);
    }
}

IEnumerator LerpLight(Light targetLight, float toIntensity, float duration)
{
    float currentIntensity = targetLight.intensity;

    float counter = 0;
    while (counter < duration)
    {
        counter += Time.deltaTime;
        targetLight.intensity = Mathf.Lerp(currentIntensity, toIntensity, counter / duration);
        yield return null;
    }
}