Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved Light glitching out when changing intensity

Discussion in 'Scripting' started by MinhocaNice, Oct 20, 2022.

  1. MinhocaNice

    MinhocaNice

    Joined:
    May 3, 2020
    Posts:
    249
    For some reason, when I try to change the intensity of the light of the Sun so that it is reduced when night comes, instead of following the script the light keeps rapidly turning on and off, apparently bouncing quickly from the correct value to 0. This is the script and I have no idea what causes this:

    Code (CSharp):
    1.  
    2.                 if (Sun != null)
    3.                 {
    4.                     Quaternion LookRotation = Quaternion.Euler(new Vector3(InGameTime / SunSpeedDivisor, 0f, 0f));
    5.                     //360f multiplied by SunSpeedDivisor is the number of seconds one in-game full day takes//
    6.                
    7.                     Sun.transform.rotation = Quaternion.Slerp(Sun.transform.rotation, LookRotation, Time.deltaTime * 5f);
    8.                     SunLight.intensity = CurrentSunLightIntensity;
    9.  
    10.                     CurrentSunLightIntensity = SunLightIntensity * Mathf.Sin(InGameTime / SunSpeedDivisor);
    11.                 }
    12.  
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,529
    This is the physics forum, it's not about graphics or general scripting.

    I'll move your post to the scripting forum.
     
    MinhocaNice likes this.
  3. kruskal21

    kruskal21

    Joined:
    May 17, 2022
    Posts:
    68
    This is probably because while Euler angles complete one full rotation in 360f degrees, the function Mathf.Sin completes one full rotation in tau (2 pi) radians, which is about 6.28f.

    To solve this, you will want to convert the result of InGameTime / SunSpeedDivisor from degrees to radians first. Using Deg2Rad.
     
    MinhocaNice likes this.
  4. MinhocaNice

    MinhocaNice

    Joined:
    May 3, 2020
    Posts:
    249
    Isn't light a physical phenomenon? I study light in physics class not art class lol.
     
  5. MinhocaNice

    MinhocaNice

    Joined:
    May 3, 2020
    Posts:
    249
    Yeah I thought about this but I was sure I read somewhere that Mathf.Sin returned in degrees... Until now that I just read the documentation of it (https://docs.unity3d.com/ScriptReference/Mathf.Sin.html) and realised it's not...

    I guess I was just crazy, let me fix that and see if it gets better.
     
  6. MinhocaNice

    MinhocaNice

    Joined:
    May 3, 2020
    Posts:
    249
    Yup, that fixed it! Works perfectly now, thanks for the help.
     
    kruskal21 likes this.