Monster.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. /// <summary>
  5. /// A monster that lives in a room.
  6. /// Behaviour:
  7. /// - Idles / wanders aimlessly within its spawn room when no agents are present.
  8. /// - When an agent enters the room, closes in to melee range and attacks each tick.
  9. /// - Each monster has its own health pool and 1d4 fist weapon.
  10. /// - When killed it fires MonsterKilled and destroys itself.
  11. /// - Represented as a red sphere identical in size to a solo agent.
  12. /// </summary>
  13. public class Monster : MonoBehaviour
  14. {
  15. // ------------------------------------------------------------------ //
  16. // Inspector //
  17. // ------------------------------------------------------------------ //
  18. [Header("Stats")]
  19. [SerializeField] private int maxHealth = 10;
  20. [SerializeField] private float movementSpeed = 1.5f;
  21. [Header("Combat")]
  22. [SerializeField] private float attackCooldown = 1.2f; // seconds between attacks
  23. [SerializeField] private float aggroRange = 12f; // range at which monsters notice agents entering
  24. [Header("Wander")]
  25. [SerializeField] private float wanderRadius = 3f;
  26. [SerializeField] private float wanderInterval = 2.5f;
  27. // ------------------------------------------------------------------ //
  28. // Runtime state //
  29. // ------------------------------------------------------------------ //
  30. private int currentHealth;
  31. private Weapon weapon;
  32. private MazeRoom homeRoom; // The room this monster belongs to
  33. private MazeData maze;
  34. private AIAgent target; // Current attack target
  35. private float lastAttackTime;
  36. private float lastWanderTime;
  37. private Vector3 wanderTarget;
  38. private bool isDead;
  39. // ------------------------------------------------------------------ //
  40. // Public interface //
  41. // ------------------------------------------------------------------ //
  42. /// <summary>
  43. /// Difficulty modifier applied during spawn (see MonsterSpawner).
  44. /// Higher = more health and slightly faster.
  45. /// </summary>
  46. public float DifficultyMultiplier { get; private set; } = 1f;
  47. public int MaxHealth => maxHealth;
  48. public int CurrentHealth => currentHealth;
  49. public bool IsDead => isDead;
  50. public MazeRoom HomeRoom => homeRoom;
  51. /// <summary>
  52. /// Convenience: threat value used by agents to estimate room danger.
  53. /// Sum of all alive monster health in a room.
  54. /// </summary>
  55. public int ThreatValue => isDead ? 0 : currentHealth;
  56. /// <summary>Fires when this monster is killed. Passes itself as argument.</summary>
  57. public System.Action<Monster> OnMonsterKilled;
  58. // ------------------------------------------------------------------ //
  59. // Initialisation //
  60. // ------------------------------------------------------------------ //
  61. /// <summary>
  62. /// Called by MonsterSpawner immediately after instantiation.
  63. /// </summary>
  64. public void Init(MazeRoom room, MazeData mazeData, float difficultyMultiplier = 1f)
  65. {
  66. homeRoom = room;
  67. maze = mazeData;
  68. DifficultyMultiplier = difficultyMultiplier;
  69. maxHealth = Mathf.RoundToInt(maxHealth * difficultyMultiplier);
  70. currentHealth = maxHealth;
  71. movementSpeed = movementSpeed * Mathf.Lerp(1f, 1.3f, difficultyMultiplier - 1f);
  72. weapon = Weapon.Fists();
  73. wanderTarget = transform.position;
  74. lastWanderTime = Time.time;
  75. }
  76. // ------------------------------------------------------------------ //
  77. // Unity loop //
  78. // ------------------------------------------------------------------ //
  79. void Update()
  80. {
  81. if (isDead || maze == null) return;
  82. AcquireTarget();
  83. if (target != null)
  84. CombatUpdate();
  85. else
  86. WanderUpdate();
  87. }
  88. // ------------------------------------------------------------------ //
  89. // Target acquisition //
  90. // ------------------------------------------------------------------ //
  91. private void AcquireTarget()
  92. {
  93. // Drop dead targets
  94. if (target != null && (target == null || target.IsDead || target.HasReachedGoal))
  95. {
  96. target = null;
  97. }
  98. if (target != null) return;
  99. // Find the nearest live agent within aggro range
  100. float bestDist = aggroRange * aggroRange;
  101. AIAgent best = null;
  102. foreach (var agent in FindObjectsByType<AIAgent>(FindObjectsSortMode.None))
  103. {
  104. if (agent.IsDead) continue;
  105. // Only aggro agents that are in or entering this room
  106. Vector2Int agentTile = WorldToTile(agent.transform.position);
  107. MazeRoom agentRoom = maze.GetRoomAtTile(agentTile.x, agentTile.y);
  108. if (agentRoom == null || agentRoom.Id != homeRoom.Id) continue;
  109. float sqDist = (agent.transform.position - transform.position).sqrMagnitude;
  110. if (sqDist < bestDist)
  111. {
  112. bestDist = sqDist;
  113. best = agent;
  114. }
  115. }
  116. target = best;
  117. }
  118. // ------------------------------------------------------------------ //
  119. // Combat //
  120. // ------------------------------------------------------------------ //
  121. private void CombatUpdate()
  122. {
  123. float dist = Vector3.Distance(transform.position, target.transform.position);
  124. if (dist > weapon.MeleeRange)
  125. {
  126. // Close in
  127. Vector3 dir = (target.transform.position - transform.position).normalized;
  128. transform.position += dir * movementSpeed * Time.deltaTime;
  129. }
  130. else
  131. {
  132. // Attack
  133. if (Time.time - lastAttackTime >= attackCooldown)
  134. {
  135. lastAttackTime = Time.time;
  136. PerformAttack();
  137. }
  138. }
  139. }
  140. private void PerformAttack()
  141. {
  142. if (target == null || target.IsDead) return;
  143. // Monsters use base hit chance — no advantage modifier
  144. if (weapon.TryHit(1f))
  145. {
  146. int dmg = weapon.RollDamage();
  147. target.TakeDamage(dmg, this);
  148. Debug.Log($"[Monster] hit {target.AgentName} for {dmg} (HP left: {target.CurrentHealth})");
  149. }
  150. else
  151. {
  152. Debug.Log($"[Monster] missed {target.AgentName}");
  153. }
  154. }
  155. // ------------------------------------------------------------------ //
  156. // Wander (no target) //
  157. // ------------------------------------------------------------------ //
  158. private void WanderUpdate()
  159. {
  160. // Move toward wander target
  161. if (Vector3.Distance(transform.position, wanderTarget) > 0.2f)
  162. {
  163. Vector3 dir = (wanderTarget - transform.position).normalized;
  164. transform.position += dir * (movementSpeed * 0.5f) * Time.deltaTime;
  165. }
  166. // Pick new wander target periodically
  167. if (Time.time - lastWanderTime > wanderInterval)
  168. {
  169. lastWanderTime = Time.time;
  170. PickNewWanderTarget();
  171. }
  172. }
  173. private void PickNewWanderTarget()
  174. {
  175. if (homeRoom == null) return;
  176. // Random tile inside home room
  177. int x = Random.Range(homeRoom.MinX + 1, homeRoom.MaxX);
  178. int y = Random.Range(homeRoom.MinY + 1, homeRoom.MaxY);
  179. wanderTarget = new Vector3(x + 0.5f, 1f, y + 0.5f);
  180. }
  181. // ------------------------------------------------------------------ //
  182. // Damage / death //
  183. // ------------------------------------------------------------------ //
  184. /// <summary>
  185. /// Deal damage to this monster. Called by agents during their attack.
  186. /// Returns true if this hit killed the monster.
  187. /// </summary>
  188. public bool TakeDamage(int amount)
  189. {
  190. if (isDead) return false;
  191. currentHealth -= amount;
  192. if (currentHealth <= 0)
  193. {
  194. Die();
  195. return true;
  196. }
  197. return false;
  198. }
  199. private void Die()
  200. {
  201. if (isDead) return;
  202. isDead = true;
  203. currentHealth = 0;
  204. Debug.Log($"[Monster] in room {homeRoom?.Id} died.");
  205. OnMonsterKilled?.Invoke(this);
  206. Destroy(gameObject);
  207. }
  208. // ------------------------------------------------------------------ //
  209. // Helpers //
  210. // ------------------------------------------------------------------ //
  211. private Vector2Int WorldToTile(Vector3 worldPos)
  212. => new Vector2Int(Mathf.FloorToInt(worldPos.x), Mathf.FloorToInt(worldPos.z));
  213. // ------------------------------------------------------------------ //
  214. // Mouse interaction – click to inspect (future) //
  215. // ------------------------------------------------------------------ //
  216. void OnMouseDown()
  217. {
  218. Debug.Log($"[Monster] Room {homeRoom?.Id} | HP {currentHealth}/{maxHealth} | Difficulty ×{DifficultyMultiplier:F1}");
  219. }
  220. }