94 lines
3.1 KiB
C#
94 lines
3.1 KiB
C#
using UnityEngine;
|
|
using System.Collections;
|
|
|
|
public class DayNightCycle : MonoBehaviour
|
|
{
|
|
[SerializeField] private Light sunlight;
|
|
[SerializeField] private GameObject sunTarget;
|
|
[SerializeField] private GameObject sunriseTarget;
|
|
[SerializeField] private GameObject sunsetTarget;
|
|
[SerializeField] private GameObject noonTarget;
|
|
[SerializeField] private float minIntensity = 0.1f;
|
|
[SerializeField] private float maxIntensity = 2f;
|
|
[SerializeField] private float sunriseTime = 21600f; // 6:00 AM
|
|
[SerializeField] private float sunsetTime = 72000f; // 8:00 PM
|
|
[SerializeField] private float noonTime = 43200f; // 12:00 PM
|
|
[SerializeField] private float dayLengthInSeconds = 120f; // Real seconds for a full day
|
|
[SerializeField] public bool isCityScriptPresent = true;
|
|
|
|
public float CurrentTime { get; private set; } = 0f;
|
|
private bool running = true;
|
|
|
|
private void Start()
|
|
{
|
|
if (!isCityScriptPresent)
|
|
{
|
|
StartCoroutine(DayNightRoutine());
|
|
}
|
|
}
|
|
|
|
private IEnumerator DayNightRoutine()
|
|
{
|
|
while (running)
|
|
{
|
|
// Advance time
|
|
CurrentTime += (86400f / dayLengthInSeconds) * Time.deltaTime;
|
|
if (CurrentTime >= 86400f)
|
|
{
|
|
CurrentTime = 0f;
|
|
// Optionally: trigger a new day event here
|
|
}
|
|
UpdateDayCycle(CurrentTime);
|
|
yield return null;
|
|
}
|
|
}
|
|
|
|
public void UpdateDayCycle(float curTime)
|
|
{
|
|
if (sunlight == null || sunTarget == null) return;
|
|
|
|
float intensity = minIntensity;
|
|
Vector3 sunPosition = sunriseTarget != null ? sunriseTarget.transform.position : Vector3.zero;
|
|
|
|
if (curTime >= sunriseTime && curTime <= sunsetTime)
|
|
{
|
|
if (curTime <= noonTime)
|
|
{
|
|
float t = (curTime - sunriseTime) / (noonTime - sunriseTime);
|
|
intensity = Mathf.Lerp(minIntensity, maxIntensity, t);
|
|
if (sunriseTarget != null && noonTarget != null)
|
|
sunPosition = Vector3.Lerp(sunriseTarget.transform.position, noonTarget.transform.position, t);
|
|
}
|
|
else
|
|
{
|
|
float t = (curTime - noonTime) / (sunsetTime - noonTime);
|
|
intensity = Mathf.Lerp(maxIntensity, minIntensity, t);
|
|
if (noonTarget != null && sunsetTarget != null)
|
|
sunPosition = Vector3.Lerp(noonTarget.transform.position, sunsetTarget.transform.position, t);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
intensity = minIntensity;
|
|
if (sunsetTarget != null)
|
|
sunPosition = sunsetTarget.transform.position;
|
|
}
|
|
|
|
sunlight.transform.position = sunPosition;
|
|
sunlight.intensity = intensity;
|
|
sunlight.transform.LookAt(sunTarget.transform.position);
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (!isCityScriptPresent)
|
|
return;
|
|
// If City script is present, expect UpdateDayCycle to be called externally with correct time
|
|
}
|
|
|
|
public void StopDayNightCycle()
|
|
{
|
|
running = false;
|
|
}
|
|
}
|