MonsterFormationGroup.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. public class MonsterFormationGroup : MonoBehaviour
  6. {
  7. public MonsterData monsterData;
  8. public Vector3 anchorPosition;
  9. public float spacing = 1.5f;
  10. public float frontRowOffset = 2f;
  11. public float cellSize = 5f;
  12. public float attackRange = 6f;
  13. public float moveDelay = 1f;
  14. public float stopAfterDistance = 5f;
  15. public float stopDuration = 2f;
  16. public float attackInterval = 1.5f;
  17. public float attackRepeatDelay = 3f;
  18. // Attack range consistency
  19. private const float ATTACK_RANGE_BUFFER = 0.5f;
  20. private float effectiveAttackRange => attackRange + ATTACK_RANGE_BUFFER;
  21. public List<MonsterController> frontRow = new();
  22. public List<MonsterController> backRow = new();
  23. public List<Vector3> frontRowPositions = new();
  24. private Transform player;
  25. public bool isChasing = false;
  26. public bool hasDetectedPlayer = false; // Track if player has been detected
  27. private float distanceTravelled = 0f;
  28. private Coroutine attackLoopCoroutine;
  29. private TeamCohesionManager cohesionManager;
  30. private void Start()
  31. {
  32. StartCoroutine(DelayedStart());
  33. }
  34. private IEnumerator DelayedStart()
  35. {
  36. while (UIUpdater.Instance == null)
  37. yield return null; // attend que UIUpdater existe
  38. player = GameObject.FindWithTag("Player")?.transform;
  39. cohesionManager = FindFirstObjectByType<TeamCohesionManager>();
  40. if (GetComponent<Collider>() == null)
  41. {
  42. SphereCollider trigger = gameObject.AddComponent<SphereCollider>();
  43. trigger.isTrigger = true;
  44. trigger.radius = 20f;
  45. }
  46. }
  47. private void OnTriggerEnter(Collider other)
  48. {
  49. if (other.CompareTag("Player"))
  50. {
  51. hasDetectedPlayer = true;
  52. if (!isChasing && attackLoopCoroutine == null)
  53. {
  54. StartChase();
  55. }
  56. }
  57. }
  58. private void OnTriggerExit(Collider other)
  59. {
  60. if (other.CompareTag("Player"))
  61. {
  62. hasDetectedPlayer = false;
  63. if (attackLoopCoroutine != null)
  64. {
  65. StopCoroutine(attackLoopCoroutine);
  66. attackLoopCoroutine = null;
  67. }
  68. isChasing = false;
  69. }
  70. }
  71. private void OnTriggerStay(Collider other)
  72. {
  73. if (other.CompareTag("Player"))
  74. {
  75. hasDetectedPlayer = true;
  76. }
  77. }
  78. public void Spawn()
  79. {
  80. int total = monsterData.monstersPerGroup;
  81. for (int i = 0; i < total; i++)
  82. {
  83. int row = i < 3 ? 0 : 1;
  84. int indexInRow = row == 0 ? i : i - 3;
  85. float xOffset = 0f;
  86. if (row == 0)
  87. {
  88. xOffset = (indexInRow - 1) * spacing;
  89. }
  90. else
  91. {
  92. if (monsterData.monstersPerGroup == 5 && indexInRow < 2)
  93. xOffset = (indexInRow - 0.5f) * spacing;
  94. else
  95. xOffset = (indexInRow - 1.5f) * spacing;
  96. }
  97. float zOffset = -row * spacing + (row == 0 ? frontRowOffset : 0);
  98. Vector3 offset = new Vector3(xOffset, 0, zOffset);
  99. Vector3 rotatedOffset = RotateOffset(offset, monsterData.defaultOrientation);
  100. Vector3 spawnPos = anchorPosition + rotatedOffset;
  101. Quaternion rotation = GetRotationFromOrientation(monsterData.defaultOrientation);
  102. GameObject m = Instantiate(monsterData.prefab, spawnPos, rotation, transform);
  103. MonsterController ctrl = m.GetComponent<MonsterController>();
  104. ctrl.data = monsterData;
  105. ctrl.formationGroup = this;
  106. if (row == 0)
  107. {
  108. frontRow.Add(ctrl);
  109. frontRowPositions.Add(spawnPos);
  110. }
  111. else
  112. {
  113. backRow.Add(ctrl);
  114. }
  115. }
  116. }
  117. public void NotifyMonsterDeath(MonsterController dead)
  118. {
  119. Vector3 deadPosition = dead.transform.position;
  120. if (frontRow.Contains(dead))
  121. {
  122. int index = frontRow.IndexOf(dead);
  123. frontRow.RemoveAt(index);
  124. if (backRow.Count > 0)
  125. {
  126. MonsterController replacement = GetClosestBacklinerTo(deadPosition);
  127. backRow.Remove(replacement);
  128. frontRow.Insert(index, replacement);
  129. StartCoroutine(MoveReplacementWithDelay(replacement, deadPosition, 2f));
  130. }
  131. }
  132. else
  133. {
  134. backRow.Remove(dead);
  135. }
  136. }
  137. IEnumerator MoveReplacementWithDelay(MonsterController replacement, Vector3 destination, float delay)
  138. {
  139. yield return new WaitForSeconds(delay);
  140. replacement.MoveTo(destination);
  141. replacement.FaceTarget(player.position);
  142. }
  143. public void StartChase()
  144. {
  145. if (!isChasing)
  146. {
  147. if (UIUpdater.Instance == null || UIUpdater.Instance.IsReady == false)
  148. {
  149. StartCoroutine(WaitForUIThenChase());
  150. return;
  151. }
  152. StartCoroutine(ChaseRoutine());
  153. }
  154. }
  155. IEnumerator WaitForUIThenChase()
  156. {
  157. while (UIUpdater.Instance == null || UIUpdater.Instance.IsReady == false)
  158. {
  159. yield return null;
  160. }
  161. StartCoroutine(ChaseRoutine());
  162. }
  163. IEnumerator ChaseRoutine()
  164. {
  165. isChasing = true;
  166. distanceTravelled = 0f;
  167. while (isChasing && hasDetectedPlayer)
  168. {
  169. if (!hasDetectedPlayer)
  170. {
  171. isChasing = false;
  172. yield break;
  173. }
  174. float distanceToPlayer = Vector3.Distance(transform.position, player.position);
  175. if (distanceToPlayer <= attackRange || IsAdjacentToPlayer())
  176. {
  177. isChasing = false;
  178. attackLoopCoroutine = StartCoroutine(LoopAttack());
  179. yield break;
  180. }
  181. Vector3 dirToPlayer = (player.position - transform.position).normalized;
  182. Vector3 step = new Vector3(Mathf.Round(dirToPlayer.x), 0, Mathf.Round(dirToPlayer.z)) * cellSize;
  183. MoveGroupBy(step);
  184. distanceTravelled += cellSize + 1f;
  185. if (distanceTravelled >= stopAfterDistance)
  186. {
  187. yield return new WaitForSeconds(stopDuration);
  188. distanceTravelled = 0f;
  189. }
  190. else
  191. {
  192. yield return new WaitForSeconds(moveDelay);
  193. }
  194. }
  195. isChasing = false;
  196. }
  197. void MoveGroupBy(Vector3 step)
  198. {
  199. foreach (var monster in frontRow.Concat(backRow))
  200. {
  201. Vector3 targetPos = monster.transform.position + step;
  202. monster.MoveTo(targetPos);
  203. monster.FaceTarget(player.position);
  204. }
  205. }
  206. private void Update()
  207. {
  208. if (!hasDetectedPlayer) return;
  209. if (player == null) return;
  210. if (isChasing || attackLoopCoroutine != null) return;
  211. if (!isChasing && attackLoopCoroutine == null)
  212. {
  213. bool anyMonsterInAttackRange = false;
  214. if (frontRow.Count > 0)
  215. {
  216. foreach (var monster in frontRow)
  217. {
  218. if (monster != null)
  219. {
  220. float monsterToPlayerDist = Vector3.Distance(monster.transform.position, player.position);
  221. if (monsterToPlayerDist <= effectiveAttackRange)
  222. {
  223. anyMonsterInAttackRange = true;
  224. break;
  225. }
  226. }
  227. }
  228. }
  229. else
  230. {
  231. return;
  232. }
  233. if (anyMonsterInAttackRange)
  234. {
  235. attackLoopCoroutine = StartCoroutine(LoopAttack());
  236. }
  237. else
  238. {
  239. StartChase();
  240. }
  241. }
  242. }
  243. bool IsPlayerInRange()
  244. {
  245. return Vector3.Distance(transform.position, player.position) <= attackRange;
  246. }
  247. IEnumerator LoopAttack()
  248. {
  249. while (true)
  250. {
  251. if (GameManager.Instance != null && GameManager.Instance.IsPlayerDead())
  252. {
  253. attackLoopCoroutine = null;
  254. yield break;
  255. }
  256. if (!hasDetectedPlayer)
  257. {
  258. attackLoopCoroutine = null;
  259. yield break;
  260. }
  261. if (cohesionManager == null || cohesionManager.groupMembers.Count == 0)
  262. {
  263. attackLoopCoroutine = null;
  264. yield break;
  265. }
  266. if (frontRow.Count == 0 && backRow.Count == 0)
  267. {
  268. attackLoopCoroutine = null;
  269. yield break;
  270. }
  271. bool anyInRange = frontRow.Any(monster =>
  272. monster != null && Vector3.Distance(monster.transform.position, player.position) <= effectiveAttackRange);
  273. if (!anyInRange)
  274. {
  275. attackLoopCoroutine = null;
  276. yield break;
  277. }
  278. foreach (var monster in frontRow.ToList())
  279. {
  280. if (monster == null) continue;
  281. if (monsterData.attackType == MonsterData.AttackType.Melee)
  282. {
  283. float distanceToPlayer = Vector3.Distance(monster.transform.position, player.position);
  284. if (distanceToPlayer > effectiveAttackRange)
  285. {
  286. continue;
  287. }
  288. monster.StopMove();
  289. monster.FaceTarget(player.position, instant: true);
  290. if (!monster.IsFacingTarget(player.position, 45f))
  291. {
  292. continue;
  293. }
  294. monster.Attack();
  295. var closest = cohesionManager.groupMembers
  296. .OrderBy(charac => Vector3.Distance(monster.transform.position, new Vector3(charac.gridX, 0, charac.gridY)))
  297. .FirstOrDefault();
  298. if (closest == null) continue;
  299. var uiController = UIUpdater.Instance?.GetUIForCharacterByName(closest.characterName);
  300. if (uiController != null)
  301. {
  302. int damage = monster.data.attackDamage;
  303. closest.currentHP -= damage;
  304. closest.currentHP = Mathf.Max(0, closest.currentHP);
  305. uiController.UpdateHPBar();
  306. uiController.ShowDamageOnCard(damage);
  307. if (closest.currentHP <= 0)
  308. {
  309. uiController.HandleCharacterDeath();
  310. }
  311. }
  312. yield return new WaitForSeconds(attackInterval);
  313. }
  314. }
  315. yield return new WaitForSeconds(attackRepeatDelay);
  316. }
  317. }
  318. MonsterController GetClosestBacklinerTo(Vector3 position)
  319. {
  320. MonsterController closest = null;
  321. float minDist = float.MaxValue;
  322. foreach (var b in backRow)
  323. {
  324. float d = Vector3.Distance(b.transform.position, position);
  325. if (d < minDist)
  326. {
  327. minDist = d;
  328. closest = b;
  329. }
  330. }
  331. return closest;
  332. }
  333. bool IsAdjacentToPlayer()
  334. {
  335. foreach (var monster in frontRow.Concat(backRow))
  336. {
  337. if (Vector3.Distance(monster.transform.position, player.position) <= cellSize + 0.5f)
  338. return true;
  339. }
  340. return false;
  341. }
  342. Vector3 RotateOffset(Vector3 offset, MonsterData.Orientation direction)
  343. {
  344. switch (direction)
  345. {
  346. case MonsterData.Orientation.North: return offset;
  347. case MonsterData.Orientation.South: return new Vector3(-offset.x, 0, -offset.z);
  348. case MonsterData.Orientation.East: return new Vector3(offset.z, 0, -offset.x);
  349. case MonsterData.Orientation.West: return new Vector3(-offset.z, 0, offset.x);
  350. default: return offset;
  351. }
  352. }
  353. Quaternion GetRotationFromOrientation(MonsterData.Orientation orientation)
  354. {
  355. switch (orientation)
  356. {
  357. case MonsterData.Orientation.North: return Quaternion.Euler(0, 0, 0);
  358. case MonsterData.Orientation.South: return Quaternion.Euler(0, 180, 0);
  359. case MonsterData.Orientation.East: return Quaternion.Euler(0, 90, 0);
  360. case MonsterData.Orientation.West: return Quaternion.Euler(0, 270, 0);
  361. default: return Quaternion.identity;
  362. }
  363. }
  364. }