GameManager.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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. returnButton.style.marginBottom = 10;
  327. // Backup return button (fallback)
  328. var backupButton = new Button(() =>
  329. {
  330. // Destroy the victory UI
  331. if (victoryUIGO != null) Destroy(victoryUIGO);
  332. // Direct scene load as fallback
  333. try
  334. {
  335. Debug.Log("🗺️ Using backup scene transition to MapScene2");
  336. UnityEngine.SceneManagement.SceneManager.LoadScene("MapScene2");
  337. }
  338. catch (System.Exception e)
  339. {
  340. Debug.LogError($"Backup scene transition failed: {e.Message}");
  341. }
  342. });
  343. backupButton.text = "Force Return to Map";
  344. backupButton.style.fontSize = 14;
  345. backupButton.style.paddingTop = 10;
  346. backupButton.style.paddingBottom = 10;
  347. backupButton.style.paddingLeft = 20;
  348. backupButton.style.paddingRight = 20;
  349. backupButton.style.backgroundColor = new Color(0.7f, 0.4f, 0.2f, 0.9f);
  350. backupButton.style.color = Color.white;
  351. backupButton.style.borderTopLeftRadius = 5;
  352. backupButton.style.borderTopRightRadius = 5;
  353. backupButton.style.borderBottomLeftRadius = 5;
  354. backupButton.style.borderBottomRightRadius = 5;
  355. // Space key hint
  356. var hint = new Label("Press SPACE or click the button to continue");
  357. hint.style.fontSize = 14;
  358. hint.style.color = Color.gray;
  359. hint.style.unityTextAlign = TextAnchor.MiddleCenter;
  360. hint.style.marginTop = 15;
  361. // Assemble UI
  362. panel.Add(title);
  363. panel.Add(message);
  364. panel.Add(returnButton);
  365. panel.Add(backupButton);
  366. panel.Add(hint);
  367. overlay.Add(panel);
  368. rootElement.Add(overlay);
  369. // Make the UI focusable for keyboard input
  370. rootElement.focusable = true;
  371. rootElement.Focus();
  372. // Handle keyboard input
  373. bool waitingForInput = true;
  374. rootElement.RegisterCallback<KeyDownEvent>((evt) =>
  375. {
  376. if (evt.keyCode == KeyCode.Space && waitingForInput)
  377. {
  378. waitingForInput = false;
  379. if (victoryUIGO != null) Destroy(victoryUIGO);
  380. OnLootingComplete();
  381. }
  382. });
  383. // Wait for user input (this coroutine will be stopped when the button is clicked or space is pressed)
  384. while (waitingForInput && victoryUIGO != null)
  385. {
  386. yield return null;
  387. }
  388. }
  389. /// <summary>
  390. /// Called when looting is complete, proceed to end battle
  391. /// </summary>
  392. private void OnLootingComplete()
  393. {
  394. Debug.Log("🏆 Battle and looting complete, returning to exploration");
  395. Debug.Log($"🏆 Called from: {System.Environment.StackTrace}");
  396. // Save any updated team data back to the game state
  397. SaveBattleResults();
  398. // Return to MapScene2 (exploration scene)
  399. StartCoroutine(ReturnToExplorationScene());
  400. }
  401. /// <summary>
  402. /// Save battle results and return to exploration
  403. /// </summary>
  404. private System.Collections.IEnumerator ReturnToExplorationScene()
  405. {
  406. Debug.Log("🗺️ Starting return to exploration scene...");
  407. // Give a brief moment for any final UI updates
  408. yield return new WaitForSeconds(0.5f);
  409. // Load the exploration scene
  410. try
  411. {
  412. Debug.Log("🗺️ Loading MapScene2...");
  413. UnityEngine.SceneManagement.SceneManager.LoadScene("MapScene2");
  414. Debug.Log("🗺️ Scene load initiated successfully");
  415. }
  416. catch (System.Exception e)
  417. {
  418. Debug.LogError($"❌ Failed to load MapScene2: {e.Message}");
  419. Debug.LogError($"Stack trace: {e.StackTrace}");
  420. // Fallback - try to find and use battle setup
  421. var battleSetup = FindFirstObjectByType<EnhancedBattleSetup>();
  422. if (battleSetup != null)
  423. {
  424. Debug.Log("🔄 Trying fallback via EnhancedBattleSetup...");
  425. battleSetup.EndBattleSession(true); // Player victory
  426. }
  427. else
  428. {
  429. Debug.LogWarning("⚠️ No scene transition method available");
  430. // Create a simple UI to inform the player
  431. GameObject errorUIGO = new GameObject("SceneLoadErrorUI");
  432. var uiDocument = errorUIGO.AddComponent<UIDocument>();
  433. var rootElement = uiDocument.rootVisualElement;
  434. var overlay = new VisualElement();
  435. overlay.style.position = Position.Absolute;
  436. overlay.style.top = 0;
  437. overlay.style.left = 0;
  438. overlay.style.right = 0;
  439. overlay.style.bottom = 0;
  440. overlay.style.backgroundColor = new Color(0.5f, 0, 0, 0.8f);
  441. overlay.style.justifyContent = Justify.Center;
  442. overlay.style.alignItems = Align.Center;
  443. var errorLabel = new Label("Scene transition failed. Please restart the game.");
  444. errorLabel.style.fontSize = 18;
  445. errorLabel.style.color = Color.white;
  446. errorLabel.style.unityTextAlign = TextAnchor.MiddleCenter;
  447. errorLabel.style.backgroundColor = new Color(0.2f, 0.2f, 0.2f, 0.9f);
  448. errorLabel.style.paddingTop = 20;
  449. errorLabel.style.paddingBottom = 20;
  450. errorLabel.style.paddingLeft = 20;
  451. errorLabel.style.paddingRight = 20;
  452. errorLabel.style.borderTopLeftRadius = 10;
  453. errorLabel.style.borderTopRightRadius = 10;
  454. errorLabel.style.borderBottomLeftRadius = 10;
  455. errorLabel.style.borderBottomRightRadius = 10;
  456. overlay.Add(errorLabel);
  457. rootElement.Add(overlay);
  458. }
  459. }
  460. }
  461. /// <summary>
  462. /// Save battle results back to persistent game state
  463. /// </summary>
  464. private void SaveBattleResults()
  465. {
  466. // Update team data with any changes from battle (health, items, etc.)
  467. var alivePlayerCharacters = GetAlivePlayers();
  468. // You could save character states here if needed
  469. Debug.Log($"💾 Saved battle results for {alivePlayerCharacters.Count} surviving players");
  470. }
  471. #region Debug and Testing Methods
  472. /// <summary>
  473. /// [DEBUG] Force battle end for testing post-battle systems
  474. /// </summary>
  475. [ContextMenu("Test Battle Victory")]
  476. public void TestBattleVictory()
  477. {
  478. Debug.Log("🧪 [TEST] Forcing battle victory to test post-battle loot system");
  479. // Kill all enemies for testing
  480. foreach (var enemy in enemyCharacters)
  481. {
  482. if (enemy != null)
  483. {
  484. var character = enemy.GetComponent<Character>();
  485. if (character != null && !character.IsDead)
  486. {
  487. // Force enemy death for testing
  488. character.TakeDamage(1000);
  489. }
  490. }
  491. }
  492. // Manually trigger victory
  493. HandlePlayerVictory(enemyCharacters);
  494. }
  495. /// <summary>
  496. /// [DEBUG] Force battle defeat for testing game over
  497. /// </summary>
  498. [ContextMenu("Test Battle Defeat")]
  499. public void TestBattleDefeat()
  500. {
  501. Debug.Log("🧪 [TEST] Forcing battle defeat to test game over screen");
  502. // Kill all players for testing
  503. foreach (var player in playerCharacters)
  504. {
  505. if (player != null)
  506. {
  507. var character = player.GetComponent<Character>();
  508. if (character != null && !character.IsDead)
  509. {
  510. // Force player death for testing
  511. character.TakeDamage(1000);
  512. }
  513. }
  514. }
  515. // Manually trigger defeat
  516. HandlePlayerDefeat(playerCharacters);
  517. }
  518. /// <summary>
  519. /// [PUBLIC] Manually trigger return to map - can be called by UI buttons or debug scripts
  520. /// </summary>
  521. public void ManualReturnToMap()
  522. {
  523. Debug.Log("🗺️ [MANUAL] Manual return to map requested");
  524. // Save any updated team data back to the game state
  525. SaveBattleResults();
  526. // Return to MapScene2 (exploration scene)
  527. StartCoroutine(ReturnToExplorationScene());
  528. }
  529. #endregion
  530. private IEnumerator ExecuteAllActionsSimultaneously()
  531. {
  532. isActionExecutionPhaseActive = true;
  533. var allActions = new Dictionary<GameObject, GameObject>();
  534. var movementActions = new Dictionary<GameObject, Vector3>();
  535. // Collect player actions from Character components
  536. foreach (GameObject playerGO in playerCharacters)
  537. {
  538. Character character = playerGO.GetComponent<Character>();
  539. if (character != null && character.actionData.hasTarget)
  540. {
  541. if (character.actionData.targetEnemy != null)
  542. {
  543. allActions[playerGO] = character.actionData.targetEnemy;
  544. }
  545. else if (character.actionData.targetPosition != Vector3.zero)
  546. {
  547. movementActions[playerGO] = character.actionData.targetPosition;
  548. }
  549. }
  550. }
  551. foreach (var action in enemySelectedTargets)
  552. {
  553. allActions[action.Key] = action.Value;
  554. }
  555. int playerActionsCount = allActions.Count - enemySelectedTargets.Count + movementActions.Count;
  556. enemySelectedTargets.Clear(); // Clear enemy targets as well
  557. if (allActions.Count == 0 && movementActions.Count == 0)
  558. {
  559. isActionExecutionPhaseActive = false;
  560. yield break;
  561. }
  562. // Configure All NavMeshAgents before starting movement
  563. foreach (var action in allActions)
  564. {
  565. GameObject actor = action.Key;
  566. if (actor == null)
  567. {
  568. continue;
  569. }
  570. Character character = actor.GetComponent<Character>();
  571. float attackRange = character != null ? character.GetAttackRange() : 2.0f;
  572. NavMeshAgent agent = actor.GetComponent<NavMeshAgent>();
  573. if (agent != null)
  574. {
  575. // For melee weapons (range <= 2), get much closer. For ranged, stay back more.
  576. float stoppingDistance = attackRange <= 2 ? 0.2f : Mathf.Max(0.5f, attackRange - 1.0f);
  577. agent.stoppingDistance = stoppingDistance;
  578. //
  579. agent.obstacleAvoidanceType = ObstacleAvoidanceType.HighQualityObstacleAvoidance;
  580. agent.avoidancePriority = UnityEngine.Random.Range(0, 100);
  581. // Start movement
  582. GameObject target = action.Value;
  583. if (target != null)
  584. {
  585. agent.SetDestination(target.transform.position);
  586. agent.isStopped = false;
  587. }
  588. }
  589. else
  590. {
  591. Debug.LogWarning($"NavMeshAgent not found or disabled on {actor.name}. Cannot move towards target.");
  592. }
  593. }
  594. // Handle pure movement actions (no enemy target)
  595. foreach (var movement in movementActions)
  596. {
  597. GameObject playerGO = movement.Key;
  598. Vector3 targetPosition = movement.Value;
  599. NavMeshAgent agent = playerGO.GetComponent<NavMeshAgent>();
  600. if (agent != null)
  601. {
  602. agent.SetDestination(targetPosition);
  603. agent.isStopped = false;
  604. }
  605. }
  606. // handle movement duration based on mode
  607. //
  608. if (allActions.Count > 0 || movementActions.Count > 0)
  609. {
  610. yield return StartCoroutine(MovementPhaseWithTargetTracking(allActions, movementActions, 1.0f));
  611. }
  612. // else
  613. // {
  614. // // If there are only attacks (no movement), still wait for 1 second
  615. // yield return new WaitForSeconds(1.0f);
  616. // }
  617. if (!isContinuousRunActive)
  618. {
  619. //
  620. //
  621. // Check for completed movement actions before showing lines
  622. CheckAndResetCompletedMovements();
  623. // Enable input and show lines for actions during pause - allow re-picking actions
  624. playerDecisionController.UpdateVisualStates(); // Update colors
  625. playerDecisionController.SetEnabled(true); // Allow action changes
  626. playerDecisionController.ShowActiveActionLines();
  627. PauseGame();
  628. waitingForAdvanceInput = true;
  629. yield return new WaitUntil(() => !waitingForAdvanceInput);
  630. // Disable input when advancing
  631. playerDecisionController.SetEnabled(false);
  632. ResumeGame();
  633. yield return new WaitForSeconds(1.0f);
  634. }
  635. foreach (var action in allActions)
  636. {
  637. GameObject actor = action.Key;
  638. GameObject target = action.Value;
  639. if (actor == null || target == null) continue;
  640. Character character = actor.GetComponent<Character>();
  641. float attackRange = character != null ? character.GetAttackRange() : 2.0f;
  642. float distance = Vector3.Distance(actor.transform.position, target.transform.position);
  643. if (distance <= attackRange)
  644. {
  645. // Execute the character's attack action
  646. character.ExecuteAction();
  647. }
  648. else
  649. {
  650. }
  651. }
  652. // Check movement completion and reset action if reached (movement actions are one-time)
  653. foreach (var movement in movementActions)
  654. {
  655. GameObject actor = movement.Key;
  656. Vector3 targetPosition = movement.Value;
  657. if (actor == null) continue;
  658. Character character = actor.GetComponent<Character>();
  659. if (character != null)
  660. {
  661. // Use horizontal distance only, ignore Y differences
  662. Vector3 actorPos = actor.transform.position;
  663. Vector2 actorPos2D = new Vector2(actorPos.x, actorPos.z);
  664. Vector2 targetPos2D = new Vector2(targetPosition.x, targetPosition.z);
  665. float horizontalDistance = Vector2.Distance(actorPos2D, targetPos2D);
  666. if (horizontalDistance <= 1.2f) // Movement completion threshold
  667. {
  668. character.actionData.Reset();
  669. character.SetVisualState(ActionDecisionState.NoAction);
  670. }
  671. }
  672. }
  673. isActionExecutionPhaseActive = false;
  674. BattleUIManager.Instance.SetButtonsInteractable(true);
  675. }
  676. private IEnumerator MovementPhaseWithTargetTracking(Dictionary<GameObject, GameObject> allActions, Dictionary<GameObject, Vector3> movementActions, float movementDuration)
  677. {
  678. float elapsedTime = 0f;
  679. // Store witch agents are still moving (not in attack range)
  680. Dictionary<NavMeshAgent, GameObject> activeMovements = new Dictionary<NavMeshAgent, GameObject>();
  681. Dictionary<NavMeshAgent, float> agentAttackRanges = new Dictionary<NavMeshAgent, float>();
  682. // Initialize active movements for attack actions
  683. foreach (var action in allActions)
  684. {
  685. GameObject actor = action.Key;
  686. GameObject target = action.Value;
  687. if (actor == null || target == null) continue;
  688. NavMeshAgent agent = actor.GetComponent<NavMeshAgent>();
  689. if (agent != null && agent.enabled)
  690. {
  691. // Get the character's attack range
  692. Character character = actor.GetComponent<Character>();
  693. float attackRange = character != null ? character.GetAttackRange() : 2.0f;
  694. // Configure agent for proper pathfinding around obstacles
  695. agent.obstacleAvoidanceType = ObstacleAvoidanceType.HighQualityObstacleAvoidance;
  696. agent.avoidancePriority = UnityEngine.Random.Range(0, 100); // Random priority to avoid clustering
  697. activeMovements[agent] = target;
  698. agentAttackRanges[agent] = attackRange;
  699. }
  700. }
  701. // Initialize active movements for pure movement actions
  702. foreach (var movement in movementActions)
  703. {
  704. GameObject actor = movement.Key;
  705. Vector3 targetPosition = movement.Value;
  706. if (actor == null) continue;
  707. NavMeshAgent agent = actor.GetComponent<NavMeshAgent>();
  708. if (agent != null && agent.enabled)
  709. {
  710. // For movement actions, use a small stopping distance to get closer
  711. float arrivalRange = 1.2f;
  712. // Configure agent for proper pathfinding around obstacles
  713. agent.obstacleAvoidanceType = ObstacleAvoidanceType.HighQualityObstacleAvoidance;
  714. agent.avoidancePriority = UnityEngine.Random.Range(0, 100);
  715. agent.stoppingDistance = 0.1f; // Get very close to the target
  716. // Create a dummy target GameObject at the position for consistency with the tracking system
  717. GameObject dummyTarget = new GameObject("MovementTarget");
  718. dummyTarget.transform.position = targetPosition;
  719. activeMovements[agent] = dummyTarget;
  720. agentAttackRanges[agent] = arrivalRange;
  721. }
  722. }
  723. while (elapsedTime < movementDuration && Time.timeScale > 0 && activeMovements.Count > 0)
  724. {
  725. var agentsToRemove = new List<NavMeshAgent>();
  726. foreach (var movement in activeMovements)
  727. {
  728. NavMeshAgent agent = movement.Key;
  729. GameObject target = movement.Value;
  730. float attackRange = agentAttackRanges[agent];
  731. if (agent == null || target == null || agent.gameObject == null)
  732. {
  733. agentsToRemove.Add(agent);
  734. continue;
  735. }
  736. float distanceToTarget = Vector3.Distance(agent.transform.position, target.transform.position);
  737. if (distanceToTarget <= attackRange)
  738. {
  739. agent.isStopped = true;
  740. agent.velocity = Vector3.zero;
  741. agentsToRemove.Add(agent);
  742. // If this is a movement target (dummy), check if we should reset the action
  743. if (target.name == "MovementTarget")
  744. {
  745. Character character = agent.GetComponent<Character>();
  746. if (character != null && character.actionData.targetPosition != Vector3.zero)
  747. {
  748. character.actionData.Reset();
  749. character.SetVisualState(ActionDecisionState.NoAction);
  750. }
  751. }
  752. }
  753. else if (!agent.isStopped)
  754. {
  755. // For movement targets, go directly to the position
  756. if (target.name == "MovementTarget")
  757. {
  758. agent.SetDestination(target.transform.position);
  759. // Check if agent has reached destination or is very close but stopped moving
  760. if (agent.pathStatus == NavMeshPathStatus.PathComplete &&
  761. (!agent.hasPath || agent.remainingDistance < 0.1f))
  762. {
  763. Character character = agent.GetComponent<Character>();
  764. if (character != null)
  765. {
  766. Vector3 actorPos = agent.transform.position;
  767. Vector3 targetPos = character.actionData.targetPosition;
  768. Vector2 actorPos2D = new Vector2(actorPos.x, actorPos.z);
  769. Vector2 targetPos2D = new Vector2(targetPos.x, targetPos.z);
  770. float horizontalDistance = Vector2.Distance(actorPos2D, targetPos2D);
  771. if (horizontalDistance <= 1.2f)
  772. {
  773. agent.isStopped = true;
  774. agentsToRemove.Add(agent);
  775. character.actionData.Reset();
  776. character.SetVisualState(ActionDecisionState.NoAction);
  777. }
  778. }
  779. }
  780. }
  781. else
  782. {
  783. // Update destination to track moving target, but stop just outside attack range
  784. Vector3 directionToTarget = (target.transform.position - agent.transform.position).normalized;
  785. Vector3 stoppingPosition = target.transform.position - directionToTarget * (attackRange * 0.9f);
  786. agent.SetDestination(stoppingPosition);
  787. }
  788. // Check if agent is stuck or can't reach destination
  789. if (agent.pathStatus == NavMeshPathStatus.PathInvalid)
  790. {
  791. Debug.LogWarning($"{agent.gameObject.name} cannot find path to {target.name}");
  792. agent.SetDestination(target.transform.position);
  793. }
  794. }
  795. }
  796. foreach (var agent in agentsToRemove)
  797. {
  798. activeMovements.Remove(agent);
  799. agentAttackRanges.Remove(agent);
  800. }
  801. yield return null; // wait one frame
  802. elapsedTime += Time.deltaTime;
  803. }
  804. // Stop any remaining moving agents and clean up dummy targets
  805. foreach (var movement in activeMovements)
  806. {
  807. if (movement.Key != null && movement.Key.enabled)
  808. {
  809. movement.Key.isStopped = true;
  810. movement.Key.velocity = Vector3.zero;
  811. }
  812. // Clean up dummy movement targets
  813. if (movement.Value != null && movement.Value.name == "MovementTarget")
  814. {
  815. Destroy(movement.Value);
  816. }
  817. }
  818. }
  819. public void AdvanceAction()
  820. {
  821. // Hide action lines when advancing
  822. if (playerDecisionController != null)
  823. {
  824. playerDecisionController.HideActiveActionLines();
  825. }
  826. if (waitingForAdvanceInput)
  827. {
  828. waitingForAdvanceInput = false;
  829. }
  830. else if (Time.timeScale == 0 && !isActionExecutionPhaseActive)
  831. {
  832. ResumeGame();
  833. }
  834. else
  835. {
  836. }
  837. }
  838. public void PauseGame()
  839. {
  840. Time.timeScale = 0f; // Pause the game
  841. BattleUIManager.Instance.SetButtonsInteractable(true);
  842. }
  843. public void ResumeGame()
  844. {
  845. Time.timeScale = 1f; // Resume the game
  846. }
  847. private void EnemiesDecideAction()
  848. {
  849. enemySelectedTargets.Clear();
  850. foreach (var enemy in enemyCharacters)
  851. {
  852. if (enemy == null)
  853. {
  854. Debug.LogWarning("Found null enemy in enemyCharacters list");
  855. continue;
  856. }
  857. if (playerCharacters.Count == 0)
  858. {
  859. Debug.LogWarning("No player characters available for enemies to target");
  860. continue;
  861. }
  862. // Logic for enemy action decision
  863. GameObject closestPlayer = null;
  864. float minDistance = float.MaxValue;
  865. List<GameObject> alivePlayers = playerCharacters.Where(player => !player.GetComponent<Character>().IsDead).ToList();
  866. foreach (var player in alivePlayers)
  867. {
  868. if (player == null) continue; // Safety check
  869. float distance = Vector3.Distance(enemy.transform.position, player.transform.position);
  870. if (distance < minDistance)
  871. {
  872. minDistance = distance;
  873. closestPlayer = player;
  874. }
  875. }
  876. if (closestPlayer != null)
  877. {
  878. // Set the enemy's action data to attack the target
  879. Character enemyCharacter = enemy.GetComponent<Character>();
  880. if (enemyCharacter != null)
  881. {
  882. enemyCharacter.actionData.SetAttackTarget(closestPlayer);
  883. }
  884. enemySelectedTargets[enemy] = closestPlayer; // Assign the closest player as the target
  885. }
  886. else
  887. {
  888. Debug.LogWarning($"{enemy.name} could not find a valid target");
  889. }
  890. enemy.GetComponent<Character>().SetVisualState(ActionDecisionState.EnemyAction);
  891. }
  892. }
  893. private void CheckAndResetCompletedMovements()
  894. {
  895. foreach (GameObject playerGO in playerCharacters)
  896. {
  897. Character character = playerGO.GetComponent<Character>();
  898. if (character != null && character.actionData.targetPosition != Vector3.zero && character.actionData.targetEnemy == null)
  899. {
  900. // This is a movement action, check if completed using horizontal distance only
  901. Vector3 playerPos = playerGO.transform.position;
  902. Vector3 targetPos = character.actionData.targetPosition;
  903. // Use only X and Z coordinates (ignore Y differences)
  904. Vector2 playerPos2D = new Vector2(playerPos.x, playerPos.z);
  905. Vector2 targetPos2D = new Vector2(targetPos.x, targetPos.z);
  906. float horizontalDistance = Vector2.Distance(playerPos2D, targetPos2D);
  907. if (horizontalDistance <= 1.2f) // Threshold for "close enough"
  908. {
  909. character.actionData.Reset();
  910. character.SetVisualState(ActionDecisionState.NoAction);
  911. }
  912. }
  913. }
  914. }
  915. }