108 lines
2.8 KiB
C#
108 lines
2.8 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
public class TimeManager : MonoBehaviour
|
|
{
|
|
public static Action OnMinuteChanged;
|
|
|
|
[SerializeField]
|
|
private float _startHour;
|
|
|
|
[SerializeField]
|
|
private Light _sunLight;
|
|
|
|
[SerializeField]
|
|
private float _sunriseHour;
|
|
[SerializeField]
|
|
private float _sunsetHour;
|
|
|
|
[SerializeField]
|
|
private Color _dayAmbientLight;
|
|
|
|
[SerializeField]
|
|
private Color _nightAmbientLight;
|
|
|
|
[SerializeField]
|
|
private AnimationCurve _lightChangeCurve;
|
|
|
|
[SerializeField]
|
|
private float _maxSunLightIntensity;
|
|
|
|
[SerializeField]
|
|
private Light _moonLight;
|
|
|
|
[SerializeField]
|
|
private float _maxMoonLightIntensity;
|
|
|
|
private TimeSpan _sunriseTime;
|
|
private TimeSpan _sunsetTime;
|
|
|
|
private float _timer;
|
|
private float _sunInitialIntensity;
|
|
|
|
[SerializeField]
|
|
private float _minuteToRealTime = 0.05f;
|
|
|
|
private static TimeSpan _currentTime;
|
|
public static TimeSpan CurrentTime => _currentTime;
|
|
|
|
// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
_sunInitialIntensity = _sunLight.intensity;
|
|
_timer = _minuteToRealTime;
|
|
_currentTime = TimeSpan.Zero + TimeSpan.FromHours(_startHour);
|
|
_sunriseTime = TimeSpan.FromHours(_sunriseHour);
|
|
_sunsetTime = TimeSpan.FromHours(_sunsetHour);
|
|
}
|
|
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
UpdateTime();
|
|
RotateSun();
|
|
}
|
|
|
|
private void UpdateTime()
|
|
{
|
|
_timer -= Time.deltaTime;
|
|
if (_timer <= 0)
|
|
{
|
|
_currentTime = _currentTime.Add(TimeSpan.FromMinutes(1));
|
|
OnMinuteChanged?.Invoke();
|
|
|
|
_timer = _minuteToRealTime;
|
|
}
|
|
}
|
|
|
|
private void RotateSun()
|
|
{
|
|
float intensityMultiplier = 1;
|
|
float timeofDay = (float)CurrentTime.TotalSeconds / 86400;
|
|
_sunLight.transform.localRotation = Quaternion.Euler((timeofDay * 360f) - 90, 170, 0);
|
|
if (_currentTime > _sunriseTime && _currentTime < _sunsetTime)
|
|
{
|
|
if (timeofDay <= 0.25f)
|
|
intensityMultiplier = Mathf.Clamp01((timeofDay - 0.23f) * (1 / 0.02f));
|
|
if (timeofDay >= 0.73f)
|
|
intensityMultiplier = Mathf.Clamp01(1 - (timeofDay - 0.73f) * (1 / 0.02f));
|
|
}
|
|
else
|
|
{
|
|
intensityMultiplier = 0;
|
|
}
|
|
_sunLight.intensity = _sunInitialIntensity * intensityMultiplier;
|
|
}
|
|
|
|
private TimeSpan CalculateTimeDifference(TimeSpan from, TimeSpan to)
|
|
{
|
|
TimeSpan diff = to - from;
|
|
if (diff.TotalSeconds < 0)
|
|
{
|
|
diff += TimeSpan.FromHours(24);
|
|
}
|
|
|
|
return diff;
|
|
}
|
|
}
|