To add some movement to the scene and make it more dynamic, I have decided to add a day/night cycle which will include.
- A 3D model for the sun which will move across the scene.
- The colour of the sun will change from white at midday, to a reddish orange at dawn and dusk and black at night.
To introduce a light source I created a new
SunLight class which will:
- Implement a simple form of the model rendering code to render the sun model.
- Calculate the lights position and colour based on the time of day.
To work out where the sun should be at any given game time, I will take the result of the mod of the current system time in milliseconds the total time per day and then divide it by the total time per day to know how far into the day we are, then multiply that by 360° to get the current angle.
At the start of the day (0 time) the sun shall be directly below the world so if we set a position directly down on the y axis and then rotate it by the current angle, this will be the position of the sun.
Again we can make use of the angle generated for the suns position to cycle the colour between black at the start of the day, reddish orange at dawn and dusk and white at mid day.
I was unsure how best to convert the angle into a colour but I started by setting the colour based on the angle using a
when statement with ranges for each of the colours.
This was a good start but the transitions needed to be smoothed out and the skybox still looks the same throughout the day.
To fix these issues I created a simple interpolation function to gradually merge from one colour to the next, this function only works as expected because at most I am changing two of the 3 colour values each time.
This was used in the when block like this:
One final issue with this was that the sun always rotated around the scenes origin and not the player position, therefore the player could walk into the path of the sun, to fix this I passed the players position to the
UpdateSunLight function and translated the sun position by the players position.
This gave the following Day/Night cycle which I am quite happy with at the moment.
The game now has some dynamic lighting in the form of a day / night cycle which is a great improvement on the previous static lighting.
The source code at this point in the project can be found here.