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.

94 lines
2.4 KiB

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