Ry Ren
Ry Ren

Reputation: 51

Change light intensity back and forth over time

How can I change the light intensity value from 3.08 back to 1.0 after 2 seconds. I have comment in my code for additional info

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

Upvotes: 2

Views: 1219

Answers (1)

Programmer
Programmer

Reputation: 125275

To lerp between two values, just use the Mathf.PingPong with the Mathf.Lerp and provide a speed the lerp should happen at.

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

If you prefer to use a duration instead of a speed variable to control the light intensity then you that is better done with a coroutine function and just the Mathf.Lerp function with a simple timer. The lerp can then be done within x seconds.

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

Usage

public Light point_light;

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

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

Upvotes: 2

Related Questions