【Unity,C#】控制方向光模拟昼夜变化的脚本
Unity.C#.模拟昼夜变化的脚本
效果
如何实现
创建TextPro用于实时显示时间
简单配置
创建空对象
加入脚本
脚本代码
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"); } }}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~