spenibus.net
2014-04-10 04:02:31 GMT

A simple day night cycle, part 5 - Applying the loop values.

Step 10: Where we apply the values -- Back in the configuration, we set the following variables: ```` float rotationSecondFactor = 1f/86400f; // rotation factor per second float earthDepth = 7f; // offset for light direction to allow longer/shorter day than half the time ```` And we go back to "Update()". To know where to position the sun, we use "rotationFactor". It is a value between 0 and 1 that tells us how far we are in a full rotation. We also apply a 2 hours offset to that factor to have our zenith at 14:00. ```` // current rotation factor with timezone (+0200) float rotationFactor = Mathf.Abs((1 + timeLogic.daySecond*rotationSecondFactor - 2f*3600f*rotationSecondFactor ) % 1); ```` We use the rotation factor to rotate the sun: ```` // rotate sun sun.position = sunPosStart; // reset sun position sun.RotateAround(earthCentre.position, earthCentre.up, 360f*rotationFactor); // set new sun position ```` As you can see, we reset to the starting position and apply the angle from there instead of rotating from the current position. This is just me being careful about micro deviations in the angle over time. I do this for the sake of accuracy. Then we update the targeting of the lights: ```` // point light towards centre sun.LookAt(earthCentre.position - new Vector3(0,earthDepth,0)); moon.LookAt(earthCentre.position - new Vector3(0,earthDepth,0)); ```` The moon being static in this implementation, we could set it in "Start()". We apply intensity and color to the lights: ```` // set light intensity sun.light.intensity = sunIntensity; moon.light.intensity = moonIntensity; // set light colors sun.light.color = sunColor; moon.light.color = moonColor; ```` We apply color to the moon object: ```` // set moon tint moon.renderer.material.color = moonTint; ```` We set the ambient light at 25% intensity: ```` RenderSettings.ambientLight = ambientTint * 0.25f; ```` And finally, we toggle shadows depending on which light is used: ```` // enable/disable shadows sun.light.shadows = (sunIntensity == 0f) ? LightShadows.None : shadowType; moon.light.shadows = (moonIntensity == 0f) ? LightShadows.None : shadowType; ```` We made sure previously never to have 2 shadow casting light at the same time, therefore we will never run into a situation where a shadow will just pop into existence or suddenly disappear because another shadow gains or loses priority. We now have a rotating sun, a shining moon, color shifts and shadows. This could be enough. But then you decide to put a skybox in your world. And you realise that even at night, the sky stays quite bright. Solving this will be the focus of the next part. This is the end of part 5. Then comes [part 6](http://spenibus.net/b/p/7/A-simple-day-night-cycle-part-6-A-better-skybox).