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.

113 lines
2.4 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using Variables;
  6. public class MonsterController : MonoBehaviour, IResettable
  7. {
  8. [SerializeField, Header("References")]
  9. Reference<float> m_light;
  10. [SerializeField]
  11. private GameObject[] m_possibleFrames;
  12. private Transform m_player;
  13. public GameObject m_defaultObject;
  14. [SerializeField]
  15. private float m_distance = 3;
  16. [SerializeField]
  17. private Vector3 m_offset = Vector3.zero;
  18. private bool m_hasChanged = false;
  19. private void OnEnable()
  20. {
  21. m_light.OnValueChanged += OnLightChange;
  22. }
  23. private void OnDisable()
  24. {
  25. m_light.OnValueChanged -= OnLightChange;
  26. }
  27. private void Start()
  28. {
  29. m_player = GameObject.FindGameObjectWithTag("Player").transform;
  30. foreach (Transform child in transform)
  31. {
  32. if (child.gameObject.activeInHierarchy)
  33. m_defaultObject = child.gameObject;
  34. }
  35. }
  36. private void ChangeRandomMonster()
  37. {
  38. GameObject[] inactiveFrames = m_possibleFrames.Where(p => !p.activeInHierarchy).ToArray();
  39. GameObject nextFrame = inactiveFrames[Random.Range(0, inactiveFrames.Length)];
  40. foreach(Transform child in transform)
  41. {
  42. child.gameObject.SetActive(child.gameObject == nextFrame);
  43. }
  44. }
  45. private void ResetMonster()
  46. {
  47. foreach (Transform child in transform)
  48. {
  49. child.gameObject.SetActive(child.gameObject == m_defaultObject);
  50. }
  51. }
  52. private void OnLightChange(float value)
  53. {
  54. float distanceToPlayer = Vector3.Distance(m_player.position, transform.position + m_offset);
  55. if (value <= 0.1 && distanceToPlayer < m_distance && !m_hasChanged)
  56. {
  57. Debug.Log(distanceToPlayer);
  58. ChangeRandomMonster();
  59. m_hasChanged = true;
  60. }
  61. else if (value <= 0)
  62. {
  63. ResetMonster();
  64. }
  65. if (value > 0.5)
  66. {
  67. m_hasChanged = false;
  68. }
  69. }
  70. public void OnLevelLoad()
  71. {
  72. }
  73. public IEnumerator OnResetStart(float time)
  74. {
  75. yield break;
  76. }
  77. public void OnResetEnd()
  78. {
  79. ResetMonster();
  80. }
  81. private void OnDrawGizmosSelected()
  82. {
  83. Gizmos.color = Color.yellow;
  84. Gizmos.DrawWireSphere(transform.position + m_offset, m_distance);
  85. }
  86. }