# How do i achieve day and night change in real time ?

Hi, I’ve used following code for achieving day and night changes in real time using a directional light. I need to set the initial position of the sun (directional light ) according to system’s time. Say user starts the game at 12pm then the sun should start from 0 degrees and rotate 90 degrees in anti clockwise direction, I’ve used following code but the initial position is not being set in it. Kindly help me with this code

``````void Update()
{
DateTime dt  = DateTime.Now;
float hourSec = (dt.Hour * 60 * 60);
float minuteSec = (dt.Minute * 60);
float sec = dt.Second;
float currentSec = hourSec + minuteSec + sec;
int divideFactor = 24 * 60 * 60;
float divident = currentSec * 360;
float degrees = divident / divideFactor;

//set flag 0
if (setInitialRotation)//wait and run initial rotation
{
transform.LookAt (target.transform);
transform.RotateAround (target.transform.position, Vector3.forward, degrees * Time.deltaTime  );
setInitialRotation = false;
}
else//run final rotation, set flag 1
{
transform.LookAt (target.transform);
transform.RotateAround (target.transform.position, Vector3.forward, (float)0.004166 * Time.deltaTime);
}

}
``````

Hi,

I’m not very convinced by your math about seconds (i just gave it a quick look maybe you can explain it a bit more): if it’s midnight in real world you’ll have 246060 seconds thus degrees will be equal to 360 or 0 (same thing) thus your directional light will be horizontal, which is ok for a night mood. But if it’s noon, you’ll have 180 degrees which will give you the same lighting (in the opposite direction) where you would want the sun to be facing the ground (which is 90 degrees).

What you could do is a switch case with your “dt.Hour” and select the good angle (if you want to be more precise you can do a sub switch case with dt.Minute), angle that you will choose “by hand”, say you put the case 12 at 90deg et the case 0 and 24 a 0 degrees (or less) you can divide angle in equal parts.

``````    void Start () {
DateTime dt = DateTime.Now;
int hourOfTheDay = dt.Hour;
Vector3 sunOrientation;

switch (hourOfTheDay)
{
// Midnight
case 0: sunOrientation = new Vector3 (...); break;

// ...

// Noon
case 12: sunOrientation = new Vector3 (...); break;

// ...

// Midnight again
case 24: sunOrientation = ... ; break;
}

}
``````

Down there you can use Lerp function from the rotation you have selected to midnight at the speed you want

``````void Update() {
transform.rotation = Quaternion.Lerp(from.rotation, to.rotation, Time.time * speed);
}
``````