evershade/Assets/Scripts/Managers/DayNightCycleManager.cs

82 lines
2.4 KiB
C#

using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering.Universal;
public class DayNightCycleManager : MonoBehaviour
{
public float dayLengthInMinutes = 15f;
public float startTimeInHours = 6f; // Start time in hours
public Light2D globalLight;
public TMP_Text timeText;
public Gradient lightColorGradient;
public Gradient lightIntensityGradient;
private float currentTime;
// possible future additions
// weather sys
// skybox changes based on time of day
// moon and stars
// clouds
// rain
// Sound effects, bird chrirping, crickets, wind, etc
// Temperture?
// Lighting effects! So that the transition is more visually appealing
// Moonlight phases based on day of month ect
// Seasons - impact the length of day, temp, weather, etc
private void Start()
{
StartCoroutine(DayNightCycleCoroutine());
}
private void Update()
{
timeText.text = GetCurrentTime();
}
private string GetCurrentTime()
{
// Calculate the current hour and minute based on the time of day
var timeOfDay = currentTime / (dayLengthInMinutes * 60);
var hours = Mathf.FloorToInt(timeOfDay * 24);
var minutes = Mathf.FloorToInt((timeOfDay * 24 - hours) * 60);
// Convert to 12-hour format and add AM/PM
var hours12 = hours % 12;
if (hours12 == 0) hours12 = 12;
var amPm = hours < 12 ? "AM" : "PM";
return string.Format("{0:D2}:{1:D2} {2}", hours12, minutes, amPm);
}
private IEnumerator DayNightCycleCoroutine()
{
while (true)
for (currentTime = startTimeInHours / 24 * dayLengthInMinutes * 60;
currentTime < dayLengthInMinutes * 60;
currentTime += Time.deltaTime)
{
// Calculate the current time of day between 0 (midnight) and 1 (next midnight)
var timeOfDay = currentTime / (dayLengthInMinutes * 60);
// Adjust the intensity of the light source based on the time of day
// The intensity never goes below 0.05
globalLight.color = lightColorGradient.Evaluate(timeOfDay);
// globalLight.intensity = Mathf.Max(Mathf.Cos(timeOfDay * 2 * Mathf.PI) * -0.5f + 0.5f, 0.05f);
globalLight.intensity = lightIntensityGradient.Evaluate(timeOfDay).a;
yield return null;
}
}
}