GameManager.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using Unity.VisualScripting;
  6. using UnityEngine;
  7. using UnityEngine.AI;
  8. using UnityEngine.Rendering.UI;
  9. using UnityEngine.UIElements;
  10. public class GameManager : MonoBehaviour
  11. {
  12. public static GameManager Instance { get; private set; }
  13. public List<GameObject> playerCharacters = new List<GameObject>();
  14. public List<GameObject> enemyCharacters = new List<GameObject>();
  15. [Header("Decision Controller")]
  16. public PlayerDecisionController playerDecisionController;
  17. private Dictionary<GameObject, GameObject> enemySelectedTargets = new Dictionary<GameObject, GameObject>();
  18. public bool isContinuousRunActive = false; // Indicates if the game is in continuous run mode
  19. private const string ENEMY_LAYER_NAME = "Enemies";
  20. private int enemyLayerMask;
  21. private bool isActionExecutionPhaseActive;
  22. private bool waitingForAdvanceInput = false;
  23. private void Awake()
  24. {
  25. if (Instance == null)
  26. {
  27. Instance = this;
  28. DontDestroyOnLoad(gameObject);
  29. // Initialize PlayerDecisionController if not set
  30. if (playerDecisionController == null)
  31. {
  32. playerDecisionController = FindFirstObjectByType<PlayerDecisionController>();
  33. if (playerDecisionController == null)
  34. {
  35. GameObject pdcGO = new GameObject("PlayerDecisionController");
  36. playerDecisionController = pdcGO.AddComponent<PlayerDecisionController>();
  37. }
  38. }
  39. int enemyLayer = LayerMask.NameToLayer(ENEMY_LAYER_NAME);
  40. if (enemyLayer == -1)
  41. {
  42. Debug.LogError($"Layer '{ENEMY_LAYER_NAME}' not found. Please create it in Project Settings > Tags and Layers, and assign your enemy prefabs to it.");
  43. // Disable functionality or handle error appropriately
  44. }
  45. else
  46. {
  47. enemyLayerMask = 1 << enemyLayer;
  48. }
  49. }
  50. else
  51. {
  52. Destroy(gameObject);
  53. return; // Avoid further initialization if this is not the singleton instance
  54. }
  55. }
  56. internal void StartBattle(List<GameObject> placedPlayerCharacters, List<GameObject> placedEnemyCharacters)
  57. {
  58. playerCharacters = placedPlayerCharacters;
  59. enemyCharacters = placedEnemyCharacters;
  60. // Refresh PlayerDecisionController with current player characters
  61. if (playerDecisionController != null)
  62. {
  63. playerDecisionController.RefreshPlayerCharacters();
  64. playerDecisionController.SetEnabled(false); // Disable initially until decision phase
  65. }
  66. // Start the battle logic here
  67. EnemiesDecideAction();
  68. StartCoroutine(MainBattleLoopCoroutine());
  69. }
  70. private IEnumerator MainBattleLoopCoroutine()
  71. {
  72. while (true) // Main battle loop
  73. {
  74. // --- Player Decision Phase ---
  75. Time.timeScale = 1f; // Ensure normal time scale for player decision phase
  76. // Check for completed movements before turn starts
  77. CheckAndResetCompletedMovements();
  78. // Keep existing actions, only allow new decisions for characters with no action
  79. playerDecisionController.UpdateVisualStates(); // Update colors: pink for no action, green for incomplete
  80. playerDecisionController.SetEnabled(true);
  81. // Show lines for any existing incomplete actions
  82. playerDecisionController.ShowActiveActionLines();
  83. // Wait for all players to make their initial decisions (only needed at turn start)
  84. while (!playerDecisionController.AllCharactersHaveActions())
  85. {
  86. yield return null; // Wait for player input through PlayerDecisionController
  87. }
  88. // Disable input during execution phase and hide action lines
  89. playerDecisionController.SetEnabled(false);
  90. playerDecisionController.HideActiveActionLines();
  91. // --- Pause point after decision (if not in continuous run mode) ---
  92. if (!isContinuousRunActive)
  93. {
  94. PauseGame();
  95. yield return new WaitUntil(() => Time.timeScale > 0 || isContinuousRunActive);
  96. }
  97. if (Time.timeScale == 0 && isContinuousRunActive)
  98. {
  99. ResumeGame();
  100. }
  101. // --- Action execution phase ---
  102. // yield return StartCoroutine(ExecutePlayerActionsCoroutine());
  103. yield return StartCoroutine(ExecuteAllActionsSimultaneously());
  104. // TODO: add ement action execution here for a full turn
  105. if (BattleUIManager.Instance != null)
  106. {
  107. BattleUIManager.Instance.SetButtonsInteractable(true);
  108. }
  109. EnemiesDecideAction(); // Enemies decide their actions after players have executed their actions
  110. // --- Post-Actions: Loop or Pause ---
  111. if (isContinuousRunActive)
  112. {
  113. if (Time.timeScale > 0)
  114. {
  115. yield return new WaitForSeconds(0.5f); // Brief delay if running
  116. }
  117. }
  118. else
  119. {
  120. PauseGame();
  121. }
  122. // Check for battle end conditions using proper alive/dead detection
  123. List<GameObject> alivePlayers = GetAlivePlayers();
  124. List<GameObject> aliveEnemies = GetAliveEnemies();
  125. // Debug: Log current battle state
  126. Debug.Log($"🔍 Battle state check: {alivePlayers.Count} alive players, {aliveEnemies.Count} alive enemies");
  127. if (alivePlayers.Count == 0 || aliveEnemies.Count == 0)
  128. {
  129. Debug.Log("🏁 BATTLE END DETECTED!");
  130. PauseGame();
  131. if (BattleUIManager.Instance != null)
  132. {
  133. BattleUIManager.Instance.DisableBattleControls(); // Disable UI controls
  134. }
  135. // Handle battle end logic
  136. if (alivePlayers.Count == 0)
  137. {
  138. Debug.Log("💀 PLAYER DEFEAT");
  139. HandlePlayerDefeat(playerCharacters);
  140. }
  141. else if (aliveEnemies.Count == 0)
  142. {
  143. Debug.Log("🏆 PLAYER VICTORY");
  144. HandlePlayerVictory(enemyCharacters);
  145. }
  146. break; // Exit the loop if battle is over
  147. }
  148. }
  149. }
  150. public List<GameObject> GetAllCharacters()
  151. {
  152. return playerCharacters.Concat(enemyCharacters).ToList();
  153. }
  154. /// <summary>
  155. /// Get all alive player characters
  156. /// </summary>
  157. public List<GameObject> GetAlivePlayers()
  158. {
  159. var alive = playerCharacters
  160. .Where(p => p != null)
  161. .Where(p =>
  162. {
  163. var character = p.GetComponent<Character>();
  164. bool isAlive = character != null && !character.IsDead;
  165. Debug.Log($"🔍 Player {p.name}: Character={character != null}, IsDead={character?.IsDead}, Alive={isAlive}");
  166. return isAlive;
  167. })
  168. .ToList();
  169. Debug.Log($"🔍 Total alive players: {alive.Count}/{playerCharacters.Count}");
  170. return alive;
  171. }
  172. /// <summary>
  173. /// Get all alive enemy characters
  174. /// </summary>
  175. public List<GameObject> GetAliveEnemies()
  176. {
  177. var alive = enemyCharacters
  178. .Where(e => e != null)
  179. .Where(e =>
  180. {
  181. var character = e.GetComponent<Character>();
  182. bool isAlive = character != null && !character.IsDead;
  183. Debug.Log($"🔍 Enemy {e.name}: Character={character != null}, IsDead={character?.IsDead}, Alive={isAlive}");
  184. return isAlive;
  185. })
  186. .ToList();
  187. Debug.Log($"🔍 Total alive enemies: {alive.Count}/{enemyCharacters.Count}");
  188. return alive;
  189. }
  190. /// <summary>
  191. /// Handle player victory (all enemies defeated)
  192. /// </summary>
  193. private void HandlePlayerVictory(List<GameObject> defeatedEnemies)
  194. {
  195. Debug.Log("🏆 Players have won the battle!");
  196. // Check if there are actually any enemies to loot
  197. bool hasLootableEnemies = false;
  198. if (defeatedEnemies != null && defeatedEnemies.Count > 0)
  199. {
  200. foreach (var enemy in defeatedEnemies)
  201. {
  202. if (enemy != null)
  203. {
  204. var character = enemy.GetComponent<Character>();
  205. if (character != null && character.IsDead)
  206. {
  207. hasLootableEnemies = true;
  208. break;
  209. }
  210. }
  211. }
  212. }
  213. if (hasLootableEnemies)
  214. {
  215. // Find or create the post-battle loot system
  216. var lootSystem = FindFirstObjectByType<PostBattleLootSystem>();
  217. if (lootSystem == null)
  218. {
  219. // Create loot system if it doesn't exist
  220. GameObject lootSystemGO = new GameObject("PostBattleLootSystem");
  221. lootSystem = lootSystemGO.AddComponent<PostBattleLootSystem>();
  222. }
  223. // Initialize and start looting
  224. lootSystem.InitializeLootSystem(defeatedEnemies);
  225. lootSystem.OnLootingComplete += OnLootingComplete;
  226. lootSystem.StartLooting();
  227. }
  228. else
  229. {
  230. // No loot to collect, show victory screen with return button
  231. Debug.Log("🏆 No loot to collect, showing victory screen");
  232. StartCoroutine(ShowVictoryScreenAndReturn());
  233. }
  234. }
  235. /// <summary>
  236. /// Handle player defeat (all players dead)
  237. /// </summary>
  238. private void HandlePlayerDefeat(List<GameObject> defeatedPlayers)
  239. {
  240. Debug.Log("💀 All players have been defeated!");
  241. // Find or create the game over screen
  242. var gameOverScreen = FindFirstObjectByType<GameOverScreen>();
  243. if (gameOverScreen == null)
  244. {
  245. // Create game over screen if it doesn't exist
  246. GameObject gameOverGO = new GameObject("GameOverScreen");
  247. gameOverScreen = gameOverGO.AddComponent<GameOverScreen>();
  248. }
  249. // Show game over screen with statistics
  250. gameOverScreen.ShowGameOver(defeatedPlayers);
  251. }
  252. /// <summary>
  253. /// Show a simple victory screen when there's no loot and allow return to map
  254. /// </summary>
  255. private System.Collections.IEnumerator ShowVictoryScreenAndReturn()
  256. {
  257. // Create a simple victory overlay using UI Toolkit or IMGUI
  258. GameObject victoryUIGO = new GameObject("VictoryUI");
  259. var uiDocument = victoryUIGO.AddComponent<UIDocument>();
  260. // Create basic victory UI
  261. var rootElement = uiDocument.rootVisualElement;
  262. // Create overlay
  263. var overlay = new VisualElement();
  264. overlay.style.position = Position.Absolute;
  265. overlay.style.top = 0;
  266. overlay.style.left = 0;
  267. overlay.style.right = 0;
  268. overlay.style.bottom = 0;
  269. overlay.style.backgroundColor = new Color(0, 0, 0, 0.8f);
  270. overlay.style.justifyContent = Justify.Center;
  271. overlay.style.alignItems = Align.Center;
  272. // Create victory panel
  273. var panel = new VisualElement();
  274. panel.style.backgroundColor = new Color(0.1f, 0.3f, 0.1f, 0.95f);
  275. panel.style.borderTopWidth = 3;
  276. panel.style.borderBottomWidth = 3;
  277. panel.style.borderLeftWidth = 3;
  278. panel.style.borderRightWidth = 3;
  279. panel.style.borderTopColor = Color.yellow;
  280. panel.style.borderBottomColor = Color.yellow;
  281. panel.style.borderLeftColor = Color.yellow;
  282. panel.style.borderRightColor = Color.yellow;
  283. panel.style.borderTopLeftRadius = 15;
  284. panel.style.borderTopRightRadius = 15;
  285. panel.style.borderBottomLeftRadius = 15;
  286. panel.style.borderBottomRightRadius = 15;
  287. panel.style.paddingTop = 40;
  288. panel.style.paddingBottom = 40;
  289. panel.style.paddingLeft = 60;
  290. panel.style.paddingRight = 60;
  291. panel.style.width = 500;
  292. // Victory title
  293. var title = new Label("🏆 VICTORY! 🏆");
  294. title.style.fontSize = 36;
  295. title.style.color = Color.yellow;
  296. title.style.unityTextAlign = TextAnchor.MiddleCenter;
  297. title.style.marginBottom = 20;
  298. title.style.unityFontStyleAndWeight = FontStyle.Bold;
  299. // Victory message
  300. var message = new Label("The enemies have been defeated!\nThe battle is won!");
  301. message.style.fontSize = 18;
  302. message.style.color = Color.white;
  303. message.style.unityTextAlign = TextAnchor.MiddleCenter;
  304. message.style.marginBottom = 30;
  305. message.style.whiteSpace = WhiteSpace.Normal;
  306. // Return button
  307. var returnButton = new Button(() =>
  308. {
  309. // Destroy the victory UI
  310. if (victoryUIGO != null) Destroy(victoryUIGO);
  311. // Proceed to return to exploration
  312. OnLootingComplete();
  313. });
  314. returnButton.text = "Return to Map";
  315. returnButton.style.fontSize = 18;
  316. returnButton.style.paddingTop = 15;
  317. returnButton.style.paddingBottom = 15;
  318. returnButton.style.paddingLeft = 30;
  319. returnButton.style.paddingRight = 30;
  320. returnButton.style.backgroundColor = new Color(0.2f, 0.7f, 0.2f, 0.9f);
  321. returnButton.style.color = Color.white;
  322. returnButton.style.borderTopLeftRadius = 8;
  323. returnButton.style.borderTopRightRadius = 8;
  324. returnButton.style.borderBottomLeftRadius = 8;
  325. returnButton.style.borderBottomRightRadius = 8;
  326. // Space key hint
  327. var hint = new Label("Press SPACE or click the button to continue");
  328. hint.style.fontSize = 14;
  329. hint.style.color = Color.gray;
  330. hint.style.unityTextAlign = TextAnchor.MiddleCenter;
  331. hint.style.marginTop = 15;
  332. // Assemble UI
  333. panel.Add(title);
  334. panel.Add(message);
  335. panel.Add(returnButton);
  336. panel.Add(hint);
  337. overlay.Add(panel);
  338. rootElement.Add(overlay);
  339. // Make the UI focusable for keyboard input
  340. rootElement.focusable = true;
  341. rootElement.Focus();
  342. // Handle keyboard input
  343. bool waitingForInput = true;
  344. rootElement.RegisterCallback<KeyDownEvent>((evt) =>
  345. {
  346. if (evt.keyCode == KeyCode.Space && waitingForInput)
  347. {
  348. waitingForInput = false;
  349. if (victoryUIGO != null) Destroy(victoryUIGO);
  350. OnLootingComplete();
  351. }
  352. });
  353. // Wait for user input (this coroutine will be stopped when the button is clicked or space is pressed)
  354. while (waitingForInput && victoryUIGO != null)
  355. {
  356. yield return null;
  357. }
  358. }
  359. /// <summary>
  360. /// Called when looting is complete, proceed to end battle
  361. /// </summary>
  362. private void OnLootingComplete()
  363. {
  364. Debug.Log("🏆 Battle and looting complete, returning to exploration");
  365. // Save any updated team data back to the game state
  366. SaveBattleResults();
  367. // Return to MapScene2 (exploration scene)
  368. StartCoroutine(ReturnToExplorationScene());
  369. }
  370. /// <summary>
  371. /// Save battle results and return to exploration
  372. /// </summary>
  373. private System.Collections.IEnumerator ReturnToExplorationScene()
  374. {
  375. // Give a brief moment for any final UI updates
  376. yield return new WaitForSeconds(0.5f);
  377. // Load the exploration scene
  378. try
  379. {
  380. UnityEngine.SceneManagement.SceneManager.LoadScene("MapScene2");
  381. }
  382. catch (System.Exception e)
  383. {
  384. Debug.LogError($"Failed to load MapScene2: {e.Message}");
  385. // Fallback - try to find and use battle setup
  386. var battleSetup = FindFirstObjectByType<EnhancedBattleSetup>();
  387. if (battleSetup != null)
  388. {
  389. battleSetup.EndBattleSession(true); // Player victory
  390. }
  391. else
  392. {
  393. Debug.LogWarning("No scene transition method available");
  394. }
  395. }
  396. }
  397. /// <summary>
  398. /// Save battle results back to persistent game state
  399. /// </summary>
  400. private void SaveBattleResults()
  401. {
  402. // Update team data with any changes from battle (health, items, etc.)
  403. var alivePlayerCharacters = GetAlivePlayers();
  404. // You could save character states here if needed
  405. Debug.Log($"💾 Saved battle results for {alivePlayerCharacters.Count} surviving players");
  406. }
  407. #region Debug and Testing Methods
  408. /// <summary>
  409. /// [DEBUG] Force battle end for testing post-battle systems
  410. /// </summary>
  411. [ContextMenu("Test Battle Victory")]
  412. public void TestBattleVictory()
  413. {
  414. Debug.Log("🧪 [TEST] Forcing battle victory to test post-battle loot system");
  415. // Kill all enemies for testing
  416. foreach (var enemy in enemyCharacters)
  417. {
  418. if (enemy != null)
  419. {
  420. var character = enemy.GetComponent<Character>();
  421. if (character != null && !character.IsDead)
  422. {
  423. // Force enemy death for testing
  424. character.TakeDamage(1000);
  425. }
  426. }
  427. }
  428. // Manually trigger victory
  429. HandlePlayerVictory(enemyCharacters);
  430. }
  431. /// <summary>
  432. /// [DEBUG] Force battle defeat for testing game over
  433. /// </summary>
  434. [ContextMenu("Test Battle Defeat")]
  435. public void TestBattleDefeat()
  436. {
  437. Debug.Log("🧪 [TEST] Forcing battle defeat to test game over screen");
  438. // Kill all players for testing
  439. foreach (var player in playerCharacters)
  440. {
  441. if (player != null)
  442. {
  443. var character = player.GetComponent<Character>();
  444. if (character != null && !character.IsDead)
  445. {
  446. // Force player death for testing
  447. character.TakeDamage(1000);
  448. }
  449. }
  450. }
  451. // Manually trigger defeat
  452. HandlePlayerDefeat(playerCharacters);
  453. }
  454. #endregion
  455. private IEnumerator ExecuteAllActionsSimultaneously()
  456. {
  457. isActionExecutionPhaseActive = true;
  458. var allActions = new Dictionary<GameObject, GameObject>();
  459. var movementActions = new Dictionary<GameObject, Vector3>();
  460. // Collect player actions from Character components
  461. foreach (GameObject playerGO in playerCharacters)
  462. {
  463. Character character = playerGO.GetComponent<Character>();
  464. if (character != null && character.actionData.hasTarget)
  465. {
  466. if (character.actionData.targetEnemy != null)
  467. {
  468. allActions[playerGO] = character.actionData.targetEnemy;
  469. }
  470. else if (character.actionData.targetPosition != Vector3.zero)
  471. {
  472. movementActions[playerGO] = character.actionData.targetPosition;
  473. }
  474. }
  475. }
  476. foreach (var action in enemySelectedTargets)
  477. {
  478. allActions[action.Key] = action.Value;
  479. }
  480. int playerActionsCount = allActions.Count - enemySelectedTargets.Count + movementActions.Count;
  481. enemySelectedTargets.Clear(); // Clear enemy targets as well
  482. if (allActions.Count == 0 && movementActions.Count == 0)
  483. {
  484. isActionExecutionPhaseActive = false;
  485. yield break;
  486. }
  487. // Configure All NavMeshAgents before starting movement
  488. foreach (var action in allActions)
  489. {
  490. GameObject actor = action.Key;
  491. if (actor == null)
  492. {
  493. continue;
  494. }
  495. Character character = actor.GetComponent<Character>();
  496. float attackRange = character != null ? character.GetAttackRange() : 2.0f;
  497. NavMeshAgent agent = actor.GetComponent<NavMeshAgent>();
  498. if (agent != null)
  499. {
  500. // For melee weapons (range <= 2), get much closer. For ranged, stay back more.
  501. float stoppingDistance = attackRange <= 2 ? 0.2f : Mathf.Max(0.5f, attackRange - 1.0f);
  502. agent.stoppingDistance = stoppingDistance;
  503. //
  504. agent.obstacleAvoidanceType = ObstacleAvoidanceType.HighQualityObstacleAvoidance;
  505. agent.avoidancePriority = UnityEngine.Random.Range(0, 100);
  506. // Start movement
  507. GameObject target = action.Value;
  508. if (target != null)
  509. {
  510. agent.SetDestination(target.transform.position);
  511. agent.isStopped = false;
  512. }
  513. }
  514. else
  515. {
  516. Debug.LogWarning($"NavMeshAgent not found or disabled on {actor.name}. Cannot move towards target.");
  517. }
  518. }
  519. // Handle pure movement actions (no enemy target)
  520. foreach (var movement in movementActions)
  521. {
  522. GameObject playerGO = movement.Key;
  523. Vector3 targetPosition = movement.Value;
  524. NavMeshAgent agent = playerGO.GetComponent<NavMeshAgent>();
  525. if (agent != null)
  526. {
  527. agent.SetDestination(targetPosition);
  528. agent.isStopped = false;
  529. }
  530. }
  531. // handle movement duration based on mode
  532. //
  533. if (allActions.Count > 0 || movementActions.Count > 0)
  534. {
  535. yield return StartCoroutine(MovementPhaseWithTargetTracking(allActions, movementActions, 1.0f));
  536. }
  537. // else
  538. // {
  539. // // If there are only attacks (no movement), still wait for 1 second
  540. // yield return new WaitForSeconds(1.0f);
  541. // }
  542. if (!isContinuousRunActive)
  543. {
  544. //
  545. //
  546. // Check for completed movement actions before showing lines
  547. CheckAndResetCompletedMovements();
  548. // Enable input and show lines for actions during pause - allow re-picking actions
  549. playerDecisionController.UpdateVisualStates(); // Update colors
  550. playerDecisionController.SetEnabled(true); // Allow action changes
  551. playerDecisionController.ShowActiveActionLines();
  552. PauseGame();
  553. waitingForAdvanceInput = true;
  554. yield return new WaitUntil(() => !waitingForAdvanceInput);
  555. // Disable input when advancing
  556. playerDecisionController.SetEnabled(false);
  557. ResumeGame();
  558. yield return new WaitForSeconds(1.0f);
  559. }
  560. foreach (var action in allActions)
  561. {
  562. GameObject actor = action.Key;
  563. GameObject target = action.Value;
  564. if (actor == null || target == null) continue;
  565. Character character = actor.GetComponent<Character>();
  566. float attackRange = character != null ? character.GetAttackRange() : 2.0f;
  567. float distance = Vector3.Distance(actor.transform.position, target.transform.position);
  568. if (distance <= attackRange)
  569. {
  570. // Execute the character's attack action
  571. character.ExecuteAction();
  572. }
  573. else
  574. {
  575. }
  576. }
  577. // Check movement completion and reset action if reached (movement actions are one-time)
  578. foreach (var movement in movementActions)
  579. {
  580. GameObject actor = movement.Key;
  581. Vector3 targetPosition = movement.Value;
  582. if (actor == null) continue;
  583. Character character = actor.GetComponent<Character>();
  584. if (character != null)
  585. {
  586. // Use horizontal distance only, ignore Y differences
  587. Vector3 actorPos = actor.transform.position;
  588. Vector2 actorPos2D = new Vector2(actorPos.x, actorPos.z);
  589. Vector2 targetPos2D = new Vector2(targetPosition.x, targetPosition.z);
  590. float horizontalDistance = Vector2.Distance(actorPos2D, targetPos2D);
  591. if (horizontalDistance <= 1.2f) // Movement completion threshold
  592. {
  593. character.actionData.Reset();
  594. character.SetVisualState(ActionDecisionState.NoAction);
  595. }
  596. }
  597. }
  598. isActionExecutionPhaseActive = false;
  599. BattleUIManager.Instance.SetButtonsInteractable(true);
  600. }
  601. private IEnumerator MovementPhaseWithTargetTracking(Dictionary<GameObject, GameObject> allActions, Dictionary<GameObject, Vector3> movementActions, float movementDuration)
  602. {
  603. float elapsedTime = 0f;
  604. // Store witch agents are still moving (not in attack range)
  605. Dictionary<NavMeshAgent, GameObject> activeMovements = new Dictionary<NavMeshAgent, GameObject>();
  606. Dictionary<NavMeshAgent, float> agentAttackRanges = new Dictionary<NavMeshAgent, float>();
  607. // Initialize active movements for attack actions
  608. foreach (var action in allActions)
  609. {
  610. GameObject actor = action.Key;
  611. GameObject target = action.Value;
  612. if (actor == null || target == null) continue;
  613. NavMeshAgent agent = actor.GetComponent<NavMeshAgent>();
  614. if (agent != null && agent.enabled)
  615. {
  616. // Get the character's attack range
  617. Character character = actor.GetComponent<Character>();
  618. float attackRange = character != null ? character.GetAttackRange() : 2.0f;
  619. // Configure agent for proper pathfinding around obstacles
  620. agent.obstacleAvoidanceType = ObstacleAvoidanceType.HighQualityObstacleAvoidance;
  621. agent.avoidancePriority = UnityEngine.Random.Range(0, 100); // Random priority to avoid clustering
  622. activeMovements[agent] = target;
  623. agentAttackRanges[agent] = attackRange;
  624. }
  625. }
  626. // Initialize active movements for pure movement actions
  627. foreach (var movement in movementActions)
  628. {
  629. GameObject actor = movement.Key;
  630. Vector3 targetPosition = movement.Value;
  631. if (actor == null) continue;
  632. NavMeshAgent agent = actor.GetComponent<NavMeshAgent>();
  633. if (agent != null && agent.enabled)
  634. {
  635. // For movement actions, use a small stopping distance to get closer
  636. float arrivalRange = 1.2f;
  637. // Configure agent for proper pathfinding around obstacles
  638. agent.obstacleAvoidanceType = ObstacleAvoidanceType.HighQualityObstacleAvoidance;
  639. agent.avoidancePriority = UnityEngine.Random.Range(0, 100);
  640. agent.stoppingDistance = 0.1f; // Get very close to the target
  641. // Create a dummy target GameObject at the position for consistency with the tracking system
  642. GameObject dummyTarget = new GameObject("MovementTarget");
  643. dummyTarget.transform.position = targetPosition;
  644. activeMovements[agent] = dummyTarget;
  645. agentAttackRanges[agent] = arrivalRange;
  646. }
  647. }
  648. while (elapsedTime < movementDuration && Time.timeScale > 0 && activeMovements.Count > 0)
  649. {
  650. var agentsToRemove = new List<NavMeshAgent>();
  651. foreach (var movement in activeMovements)
  652. {
  653. NavMeshAgent agent = movement.Key;
  654. GameObject target = movement.Value;
  655. float attackRange = agentAttackRanges[agent];
  656. if (agent == null || target == null || agent.gameObject == null)
  657. {
  658. agentsToRemove.Add(agent);
  659. continue;
  660. }
  661. float distanceToTarget = Vector3.Distance(agent.transform.position, target.transform.position);
  662. if (distanceToTarget <= attackRange)
  663. {
  664. agent.isStopped = true;
  665. agent.velocity = Vector3.zero;
  666. agentsToRemove.Add(agent);
  667. // If this is a movement target (dummy), check if we should reset the action
  668. if (target.name == "MovementTarget")
  669. {
  670. Character character = agent.GetComponent<Character>();
  671. if (character != null && character.actionData.targetPosition != Vector3.zero)
  672. {
  673. character.actionData.Reset();
  674. character.SetVisualState(ActionDecisionState.NoAction);
  675. }
  676. }
  677. }
  678. else if (!agent.isStopped)
  679. {
  680. // For movement targets, go directly to the position
  681. if (target.name == "MovementTarget")
  682. {
  683. agent.SetDestination(target.transform.position);
  684. // Check if agent has reached destination or is very close but stopped moving
  685. if (agent.pathStatus == NavMeshPathStatus.PathComplete &&
  686. (!agent.hasPath || agent.remainingDistance < 0.1f))
  687. {
  688. Character character = agent.GetComponent<Character>();
  689. if (character != null)
  690. {
  691. Vector3 actorPos = agent.transform.position;
  692. Vector3 targetPos = character.actionData.targetPosition;
  693. Vector2 actorPos2D = new Vector2(actorPos.x, actorPos.z);
  694. Vector2 targetPos2D = new Vector2(targetPos.x, targetPos.z);
  695. float horizontalDistance = Vector2.Distance(actorPos2D, targetPos2D);
  696. if (horizontalDistance <= 1.2f)
  697. {
  698. agent.isStopped = true;
  699. agentsToRemove.Add(agent);
  700. character.actionData.Reset();
  701. character.SetVisualState(ActionDecisionState.NoAction);
  702. }
  703. }
  704. }
  705. }
  706. else
  707. {
  708. // Update destination to track moving target, but stop just outside attack range
  709. Vector3 directionToTarget = (target.transform.position - agent.transform.position).normalized;
  710. Vector3 stoppingPosition = target.transform.position - directionToTarget * (attackRange * 0.9f);
  711. agent.SetDestination(stoppingPosition);
  712. }
  713. // Check if agent is stuck or can't reach destination
  714. if (agent.pathStatus == NavMeshPathStatus.PathInvalid)
  715. {
  716. Debug.LogWarning($"{agent.gameObject.name} cannot find path to {target.name}");
  717. agent.SetDestination(target.transform.position);
  718. }
  719. }
  720. }
  721. foreach (var agent in agentsToRemove)
  722. {
  723. activeMovements.Remove(agent);
  724. agentAttackRanges.Remove(agent);
  725. }
  726. yield return null; // wait one frame
  727. elapsedTime += Time.deltaTime;
  728. }
  729. // Stop any remaining moving agents and clean up dummy targets
  730. foreach (var movement in activeMovements)
  731. {
  732. if (movement.Key != null && movement.Key.enabled)
  733. {
  734. movement.Key.isStopped = true;
  735. movement.Key.velocity = Vector3.zero;
  736. }
  737. // Clean up dummy movement targets
  738. if (movement.Value != null && movement.Value.name == "MovementTarget")
  739. {
  740. Destroy(movement.Value);
  741. }
  742. }
  743. }
  744. public void AdvanceAction()
  745. {
  746. // Hide action lines when advancing
  747. if (playerDecisionController != null)
  748. {
  749. playerDecisionController.HideActiveActionLines();
  750. }
  751. if (waitingForAdvanceInput)
  752. {
  753. waitingForAdvanceInput = false;
  754. }
  755. else if (Time.timeScale == 0 && !isActionExecutionPhaseActive)
  756. {
  757. ResumeGame();
  758. }
  759. else
  760. {
  761. }
  762. }
  763. public void PauseGame()
  764. {
  765. Time.timeScale = 0f; // Pause the game
  766. BattleUIManager.Instance.SetButtonsInteractable(true);
  767. }
  768. public void ResumeGame()
  769. {
  770. Time.timeScale = 1f; // Resume the game
  771. }
  772. private void EnemiesDecideAction()
  773. {
  774. enemySelectedTargets.Clear();
  775. foreach (var enemy in enemyCharacters)
  776. {
  777. if (enemy == null)
  778. {
  779. Debug.LogWarning("Found null enemy in enemyCharacters list");
  780. continue;
  781. }
  782. if (playerCharacters.Count == 0)
  783. {
  784. Debug.LogWarning("No player characters available for enemies to target");
  785. continue;
  786. }
  787. // Logic for enemy action decision
  788. GameObject closestPlayer = null;
  789. float minDistance = float.MaxValue;
  790. List<GameObject> alivePlayers = playerCharacters.Where(player => !player.GetComponent<Character>().IsDead).ToList();
  791. foreach (var player in alivePlayers)
  792. {
  793. if (player == null) continue; // Safety check
  794. float distance = Vector3.Distance(enemy.transform.position, player.transform.position);
  795. if (distance < minDistance)
  796. {
  797. minDistance = distance;
  798. closestPlayer = player;
  799. }
  800. }
  801. if (closestPlayer != null)
  802. {
  803. // Set the enemy's action data to attack the target
  804. Character enemyCharacter = enemy.GetComponent<Character>();
  805. if (enemyCharacter != null)
  806. {
  807. enemyCharacter.actionData.SetAttackTarget(closestPlayer);
  808. }
  809. enemySelectedTargets[enemy] = closestPlayer; // Assign the closest player as the target
  810. }
  811. else
  812. {
  813. Debug.LogWarning($"{enemy.name} could not find a valid target");
  814. }
  815. enemy.GetComponent<Character>().SetVisualState(ActionDecisionState.EnemyAction);
  816. }
  817. }
  818. private void CheckAndResetCompletedMovements()
  819. {
  820. foreach (GameObject playerGO in playerCharacters)
  821. {
  822. Character character = playerGO.GetComponent<Character>();
  823. if (character != null && character.actionData.targetPosition != Vector3.zero && character.actionData.targetEnemy == null)
  824. {
  825. // This is a movement action, check if completed using horizontal distance only
  826. Vector3 playerPos = playerGO.transform.position;
  827. Vector3 targetPos = character.actionData.targetPosition;
  828. // Use only X and Z coordinates (ignore Y differences)
  829. Vector2 playerPos2D = new Vector2(playerPos.x, playerPos.z);
  830. Vector2 targetPos2D = new Vector2(targetPos.x, targetPos.z);
  831. float horizontalDistance = Vector2.Distance(playerPos2D, targetPos2D);
  832. if (horizontalDistance <= 1.2f) // Threshold for "close enough"
  833. {
  834. character.actionData.Reset();
  835. character.SetVisualState(ActionDecisionState.NoAction);
  836. }
  837. }
  838. }
  839. }
  840. }