DayTimeManager.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public enum RotationAxis
  5. {
  6. X, Y
  7. }
  8. public class DayTimeManager : MonoBehaviour {
  9. public Light sunlight;
  10. public float secondsPerDay;
  11. public RotationAxis rotAxis = RotationAxis.X;
  12. public float maxAngle = 50.0f;
  13. private float _elapsedTime;
  14. public float timeFactor {
  15. get {
  16. return _elapsedTime / secondsPerDay;
  17. }
  18. }
  19. public DayTimeLabel dayTimeLabel {
  20. get {
  21. if (timeFactor >= 6.0f / 24.0f && timeFactor < 11.0f / 24.0f)
  22. {
  23. return DayTimeLabel.Morning;
  24. }
  25. if (timeFactor >= 11.0f / 24.0f && timeFactor < 17.0f / 24.0f)
  26. {
  27. return DayTimeLabel.Noon;
  28. }
  29. if (timeFactor >= 17.0f / 24.0f && timeFactor < 22.0f / 24.0f)
  30. {
  31. return DayTimeLabel.Evening;
  32. }
  33. if (timeFactor >= 23.0f / 24.0f && timeFactor < 24.0f / 24.0f)
  34. {
  35. return DayTimeLabel.Night;
  36. }
  37. if (timeFactor >= 0.0f / 24.0f && timeFactor < 6.0f / 24.0f)
  38. {
  39. return DayTimeLabel.Night;
  40. }
  41. return DayTimeLabel.Morning;
  42. }
  43. }
  44. private float _timeDirection = 1.0f;
  45. private Vector3 _position;
  46. private Vector3 _rotation;
  47. void Awake () {
  48. }
  49. // Use this for initialization
  50. void Start () {
  51. _position = sunlight.gameObject.transform.position;
  52. _rotation = sunlight.gameObject.transform.rotation.ToEulerAngles();
  53. }
  54. // Update is called once per frame
  55. void Update () {
  56. _elapsedTime += Time.deltaTime;
  57. if (_elapsedTime >= secondsPerDay)
  58. {
  59. _elapsedTime = 0;
  60. }
  61. float intensityAngle = this.timeFactor * Mathf.PI;
  62. sunlight.intensity = Mathf.Sin(intensityAngle);
  63. float rotationDirection = Mathf.Sign(this.timeFactor - 0.5f);
  64. switch (rotAxis)
  65. {
  66. case RotationAxis.X:
  67. {
  68. sunlight.gameObject.transform.rotation.SetEulerAngles(_rotation.x + rotationDirection * maxAngle, _rotation.y, _rotation.z);
  69. } break;
  70. case RotationAxis.Y:
  71. {
  72. sunlight.gameObject.transform.rotation.SetEulerAngles(_rotation.x, _rotation.y + rotationDirection * maxAngle, _rotation.z);
  73. } break;
  74. }
  75. }
  76. float FactorToDayTime(float factor)
  77. {
  78. return factor * 24.0f;
  79. }
  80. float DayTimeToFactor(float dayTime)
  81. {
  82. return dayTime / 24.0f;
  83. }
  84. }