效果
如何实现
using System;
using TMPro;
using UnityEngine;
public class TimeController : MonoBehaviour
{
///
/// 显示24小时制时间
///
[SerializeField]
private TextMeshProUGUI txtTime;
///
/// 定向光
///
[SerializeField]
private Light sunLight;
///
/// 时间的增长步长
///
[SerializeField]
private float timeStep = 1000;
///
/// 起始小时
///
[SerializeField]
private int startHour = 12;
///
/// 日升小时
///
[SerializeField]
private int sunriseHour = 6;
///
/// 日落小时
///
[SerializeField]
private int sunsetHour = 18;
private DateTime currentTime;
private TimeSpan sunriseTime;
private TimeSpan sunsetTime;
void Start()
{
currentTime = DateTime.Now.Date + TimeSpan.FromHours(startHour);
sunriseTime = TimeSpan.FromHours(sunriseHour);
sunsetTime = TimeSpan.FromHours(sunsetHour);
}
void Update()
{
updateTime();
updateDirectionLight();
}
///
/// 更新光照角度
///
private void updateDirectionLight()
{
float lightDegree = 0f;
if (currentTime.TimeOfDay > sunriseTime && currentTime.TimeOfDay < sunsetTime)//白天
{
TimeSpan sunrise2SunsetInterval = getTimeInterval(sunriseTime, sunsetTime);
TimeSpan sunrise2CurrentInterval = getTimeInterval(sunriseTime, currentTime.TimeOfDay);
//算出比率:当前时间差和总时间
double percentage = sunrise2CurrentInterval.TotalMilliseconds / sunrise2SunsetInterval.TotalMilliseconds;
lightDegree = Mathf.Lerp(0, 180, (float)percentage);
}
else//夜晚
{
TimeSpan sunset2SunriseInterval = getTimeInterval(sunsetTime, sunriseTime);
TimeSpan sunset2CurrentInterval = getTimeInterval(sunsetTime, currentTime.TimeOfDay);
//算出比率:当前时间差和总时间
double percentage = sunset2CurrentInterval.TotalMilliseconds / sunset2SunriseInterval.TotalMilliseconds;
lightDegree = Mathf.Lerp(180, 360, (float)percentage);
}
//根据当前时间, 将表示日光的定向光旋转到对应的角度,围绕X轴旋转
sunLight.transform.rotation = Quaternion.AngleAxis(lightDegree, Vector3.right);
}
///
/// 计算时间差
///
///
///
///
private TimeSpan getTimeInterval(TimeSpan firstTime, TimeSpan secondTime)
{
TimeSpan interval = secondTime - firstTime;
if (interval.TotalSeconds < 0)
{
interval += TimeSpan.FromHours(24);
}
return interval;
}
///
/// 更新时间
///
private void updateTime()
{
currentTime = currentTime.AddSeconds(Time.deltaTime * timeStep);
if (txtTime != null)
{
txtTime.text = currentTime.ToString("HH:mm");
}
}
}