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.

100 lines
2.4 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, BoxGroup("Settings")]
  15. private float m_darknessSpeed = 0.25f;
  16. [SerializeField, BoxGroup("Settings")]
  17. private float m_lightSpeed = 1.0f;
  18. [SerializeField, BoxGroup("Settings")]
  19. private AnimationCurve m_lightCurve = AnimationCurve.Linear(0,0,1,1);
  20. [ShowNonSerializedField]
  21. private bool m_isDarknessChanging;
  22. private void OnEnable()
  23. {
  24. m_isInputDown.OnValueChanged += OnInputChange;
  25. m_darknessMat.SetFloat("_Apply", 1);
  26. m_lightLevel.Value = 1;
  27. }
  28. private void OnDisable()
  29. {
  30. m_isInputDown.OnValueChanged -= OnInputChange;
  31. m_darknessMat.SetFloat("_Apply", 1);
  32. m_lightLevel.Value = 1;
  33. }
  34. private void OnInputChange(bool value)
  35. {
  36. StopAllCoroutines();
  37. Debug.Log($"Here {m_isDarknessChanging}");
  38. if (value)
  39. { if (!m_isDarknessChanging)
  40. {
  41. StartCoroutine(ChangeDarkness(0, m_darknessSpeed));
  42. }
  43. else
  44. {
  45. StartCoroutine(ChangeDarkness(0, 0));
  46. }
  47. }
  48. else
  49. StartCoroutine(ChangeDarkness(1, m_lightSpeed, m_lightCurve));
  50. }
  51. private IEnumerator ChangeDarkness(float end, float time)
  52. {
  53. yield return StartCoroutine(ChangeDarkness(end, time, AnimationCurve.Linear(0, 0, 1, 1)));
  54. }
  55. private IEnumerator ChangeDarkness(float end, float time, AnimationCurve curve)
  56. {
  57. float start = m_lightLevel;
  58. float elapsedTime = 0;
  59. time = Mathf.InverseLerp(end, start, m_lightLevel) * time;
  60. m_isDarknessChanging = true;
  61. while(elapsedTime < time)
  62. {
  63. m_lightLevel.Value = Mathf.Lerp(start, end, curve.Evaluate(elapsedTime / time));
  64. m_darknessMat.SetFloat("_Apply", m_lightLevel);
  65. yield return new WaitForEndOfFrame();
  66. elapsedTime += Time.deltaTime;
  67. }
  68. m_isDarknessChanging = false;
  69. m_lightLevel.Value = end;
  70. m_darknessMat.SetFloat("_Apply", m_lightLevel);
  71. }
  72. }