Global Game Jam 2022
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.5 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using NaughtyAttributes;
  5. using Variables;
  6. public class DarknessController : MonoBehaviour
  7. {
  8. [SerializeField, Header("References")]
  9. private Material m_darknessMat;
  10. [SerializeField]
  11. private Reference<float> m_lightLevel;
  12. [SerializeField]
  13. private Reference<bool> m_isInputDown;
  14. [SerializeField]
  15. private Reference<bool> m_manuelDarknesscontrol;
  16. [SerializeField, BoxGroup("Settings")]
  17. private float m_darknessSpeed = 0.25f;
  18. [SerializeField, BoxGroup("Settings")]
  19. private float m_lightSpeed = 1.0f;
  20. [SerializeField, BoxGroup("Settings")]
  21. private AnimationCurve m_lightCurve = AnimationCurve.Linear(0,0,1,1);
  22. [ShowNonSerializedField]
  23. private bool m_isDarknessChanging;
  24. private void OnEnable()
  25. {
  26. m_isInputDown.OnValueChanged += OnInputChange;
  27. m_darknessMat.SetFloat("_Apply", 1);
  28. m_lightLevel.Value = 1;
  29. }
  30. private void OnDisable()
  31. {
  32. m_isInputDown.OnValueChanged -= OnInputChange;
  33. m_darknessMat.SetFloat("_Apply", 1);
  34. m_lightLevel.Value = 1;
  35. }
  36. private void Update()
  37. {
  38. m_darknessMat.SetFloat("_Apply", m_lightLevel);
  39. }
  40. private void OnInputChange(bool value)
  41. {
  42. if (m_manuelDarknesscontrol)
  43. return;
  44. StopAllCoroutines();
  45. if (value)
  46. { if (!m_isDarknessChanging)
  47. {
  48. StartCoroutine(ChangeDarkness(0, m_darknessSpeed));
  49. }
  50. else
  51. {
  52. StartCoroutine(ChangeDarkness(0, 0));
  53. }
  54. }
  55. else
  56. StartCoroutine(ChangeDarkness(1, m_lightSpeed, m_lightCurve));
  57. }
  58. private IEnumerator ChangeDarkness(float end, float time)
  59. {
  60. yield return StartCoroutine(ChangeDarkness(end, time, AnimationCurve.Linear(0, 0, 1, 1)));
  61. }
  62. private IEnumerator ChangeDarkness(float end, float time, AnimationCurve curve)
  63. {
  64. float start = m_lightLevel;
  65. float elapsedTime = 0;
  66. time = Mathf.InverseLerp(end, start, m_lightLevel) * time;
  67. m_isDarknessChanging = true;
  68. while(elapsedTime < time)
  69. {
  70. m_lightLevel.Value = Mathf.Lerp(start, end, curve.Evaluate(elapsedTime / time));
  71. yield return new WaitForEndOfFrame();
  72. elapsedTime += Time.deltaTime;
  73. }
  74. m_isDarknessChanging = false;
  75. m_lightLevel.Value = end;
  76. }
  77. }