Igor
Igor

Reputation: 4003

Unity3D - How to control Light.Intensity without animation

I have the following animation:

See on video: Animation Light

Note: Below image of animation control

enter image description here

How can I get the same result using a script? My intention is that the script has no "if".

Don't like this:

    public float minIntensity;
    public float maxIntensity;

    public float intensityAmount;

    private Light light;

    void Awake(){
        light  = GetComponent<Light>();
    }

    void Update(){

        if (light.intensity > maxIntensity) {
            light.intensity -= intensityAmount * Time.deltaTime;
        }
        else if (light.intensity < minIntensity) {
            light.intensity += intensityAmount * Time.deltaTime;
        }   


    }

I wonder if there is any possibility to do this using some native function ... like: (Math.Clamp, Math.Lerp, Quaternion.Slerp) without any condition as "if" in the code.

Thank you in advance.

Upvotes: 0

Views: 1491

Answers (1)

Formic
Formic

Reputation: 650

Well like you mentioned, you can just use a clamp:

light.intensity = Mathf.Clamp(value, minIntensity, maxIntensity)

However, despite the lack of detail on what type of animation you want, I am assuming you want to "ping pong" between the min and the max. If that is the case, we can use our friendly neighborhood sine wave for that.

public float Frequency = 10f;  
public float Magnitude = 2f;

void Update() {
    light.Intensity = Magnitude + Mathf.Sin(Time.timeSinceLevelLoad * Frequency) * Magnitude;
}

The sine wave will go from -1 to 1, the magnitude value will make it go from (-magnitude to +magnitude) Since we don't want a negative light intensity, we add magnitude to the start, so the end result is (0 to 2 * magnitude) You can change this to work however you desire, but the point should be clear.

The Frequency variable will change how fast we animate back and forth.

Upvotes: 1

Related Questions