我正在嘗試制作一個晝夜回圈,它還可以跟蹤過去了多少天。我看了一個教程開始,對于這篇文章,我洗掉了所有不必要的東西,比如旋轉太陽和改變顏色。
public class TimeController : MonoBehaviour
{
[SerializeField]
private float timeMultiplier;
[SerializeField]
private float startHour;
private DateTime currentTime;
void Start()
{
currentTime = DateTime.Now.Date TimeSpan.FromHours(startHour);
}
void Update()
{
UpdateTimeOfDay();
}
private void UpdateTimeOfDay()
{
currentTime = currentTime.AddSeconds(Time.deltaTime * timeMultiplier);
}
}
我遇到的最大問題是,timeMultiplier我寧愿有一個dayLength變數,它代表一天應該持續多長時間,所以一天是 10 分鐘int dayLength = 600;或類似的東西,但我不確定我將如何實作.
另外,我嘗試添加一個方法來檢查一天是否已經過去,但代碼最終運行了 20 次。
public int currentDay = 1;
private void HasDayPassed()
{
if (currentTime.Hour == 0)
{
Debug.Log("New day");
currentDay ;
}
}
uj5u.com熱心網友回復:
試試這個代碼
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TimeController : MonoBehaviour
{
public const float SecondsInDay = 86400f;
[SerializeField] [Range(0, SecondsInDay)] private float _realtimeDayLength = 60;
[SerializeField] private float _startHour;
private DateTime _currentTime;
private DateTime _lastDayTime;
private int _currentDay = 1;
private void Start()
{
_currentTime = DateTime.Now TimeSpan.FromHours(_startHour);
_lastDayTime = _currentTime;
}
private void Update()
{
// Calculate a seconds step that we need to add to the current time
float secondsStep = SecondsInDay / _realtimeDayLength * Time.deltaTime;
_currentTime = _currentTime.AddSeconds(secondsStep);
// Check and increment the days passed
TimeSpan difference = _currentTime - _lastDayTime;
if(difference.TotalSeconds >= SecondsInDay)
{
_lastDayTime = _currentTime;
_currentDay ;
}
// Next do your animation stuff
AnimateSun();
}
private void AnimateSun()
{
// Animate sun however you want
}
}
您還可以洗掉范圍屬性以指定比實時日期更慢的日期。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/483847.html
標籤:unity3d
下一篇:如何在Unity中移動物件
