GameManager.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  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. // Configure movement speed based on character's MovementSpeed stat
  579. if (character != null)
  580. {
  581. // Convert character movement speed to NavMeshAgent speed (HALVED for better gameplay)
  582. // Base conversion: MovementSpeed 10 = 1.75 units/sec, scale from there
  583. agent.speed = (character.MovementSpeed / 10f) * 1.75f;
  584. // Set high acceleration to reach max speed quickly
  585. agent.acceleration = agent.speed * 3.0f; // Reach max speed in ~0.33 seconds
  586. }
  587. else
  588. {
  589. agent.speed = 1.75f; // Default speed if no character component (halved)
  590. agent.acceleration = 5.25f; // Default acceleration (halved)
  591. }
  592. //
  593. agent.obstacleAvoidanceType = ObstacleAvoidanceType.HighQualityObstacleAvoidance;
  594. agent.avoidancePriority = UnityEngine.Random.Range(0, 100);
  595. // Start movement
  596. GameObject target = action.Value;
  597. if (target != null)
  598. {
  599. agent.SetDestination(target.transform.position);
  600. agent.isStopped = false;
  601. }
  602. }
  603. else
  604. {
  605. Debug.LogWarning($"NavMeshAgent not found or disabled on {actor.name}. Cannot move towards target.");
  606. }
  607. }
  608. // Handle pure movement actions (no enemy target)
  609. foreach (var movement in movementActions)
  610. {
  611. GameObject playerGO = movement.Key;
  612. Vector3 targetPosition = movement.Value;
  613. NavMeshAgent agent = playerGO.GetComponent<NavMeshAgent>();
  614. if (agent != null)
  615. {
  616. // Configure movement speed for pure movement actions based on character's MovementSpeed stat
  617. Character character = playerGO.GetComponent<Character>();
  618. if (character != null)
  619. {
  620. // Convert character movement speed to NavMeshAgent speed (HALVED for better gameplay)
  621. // Base conversion: MovementSpeed 10 = 1.75 units/sec, scale from there
  622. agent.speed = (character.MovementSpeed / 10f) * 1.75f;
  623. // Set high acceleration to reach max speed quickly
  624. agent.acceleration = agent.speed * 3.0f; // Reach max speed in ~0.33 seconds
  625. Debug.Log($"🚀 MOVEMENT DEBUG - {character.CharacterName}: MovementSpeed={character.MovementSpeed}, AgentSpeed={agent.speed:F1}, Acceleration={agent.acceleration:F1}, TimeScale={Time.timeScale}");
  626. }
  627. else
  628. {
  629. agent.speed = 1.75f; // Default speed if no character component (halved)
  630. agent.acceleration = 5.25f; // Default acceleration (halved)
  631. Debug.Log($"🚀 MOVEMENT DEBUG - {playerGO.name}: DEFAULT AgentSpeed={agent.speed:F1}, Acceleration={agent.acceleration:F1}, TimeScale={Time.timeScale}");
  632. }
  633. agent.SetDestination(targetPosition);
  634. agent.isStopped = false;
  635. }
  636. }
  637. // handle movement duration based on mode
  638. //
  639. if (allActions.Count > 0 || movementActions.Count > 0)
  640. {
  641. yield return StartCoroutine(MovementPhaseWithTargetTracking(allActions, movementActions, 1.0f));
  642. }
  643. // else
  644. // {
  645. // // If there are only attacks (no movement), still wait for 1 second
  646. // yield return new WaitForSeconds(1.0f);
  647. // }
  648. if (!isContinuousRunActive)
  649. {
  650. //
  651. //
  652. // Check for completed movement actions before showing lines
  653. CheckAndResetCompletedMovements();
  654. // Enable input and show lines for actions during pause - allow re-picking actions
  655. playerDecisionController.UpdateVisualStates(); // Update colors
  656. playerDecisionController.SetEnabled(true); // Allow action changes
  657. playerDecisionController.ShowActiveActionLines();
  658. PauseGame();
  659. waitingForAdvanceInput = true;
  660. yield return new WaitUntil(() => !waitingForAdvanceInput);
  661. // Disable input when advancing
  662. playerDecisionController.SetEnabled(false);
  663. ResumeGame();
  664. yield return new WaitForSeconds(1.0f);
  665. }
  666. foreach (var action in allActions)
  667. {
  668. GameObject actor = action.Key;
  669. GameObject target = action.Value;
  670. if (actor == null || target == null) continue;
  671. Character character = actor.GetComponent<Character>();
  672. float attackRange = character != null ? character.GetAttackRange() : 2.0f;
  673. float distance = Vector3.Distance(actor.transform.position, target.transform.position);
  674. if (distance <= attackRange)
  675. {
  676. // Execute the character's attack action
  677. character.ExecuteAction();
  678. }
  679. else
  680. {
  681. }
  682. }
  683. // Check movement completion and reset action if reached (movement actions are one-time)
  684. foreach (var movement in movementActions)
  685. {
  686. GameObject actor = movement.Key;
  687. Vector3 targetPosition = movement.Value;
  688. if (actor == null) continue;
  689. Character character = actor.GetComponent<Character>();
  690. if (character != null)
  691. {
  692. // Use horizontal distance only, ignore Y differences
  693. Vector3 actorPos = actor.transform.position;
  694. Vector2 actorPos2D = new Vector2(actorPos.x, actorPos.z);
  695. Vector2 targetPos2D = new Vector2(targetPosition.x, targetPosition.z);
  696. float horizontalDistance = Vector2.Distance(actorPos2D, targetPos2D);
  697. if (horizontalDistance <= 1.2f) // Movement completion threshold
  698. {
  699. character.actionData.Reset();
  700. character.SetVisualState(ActionDecisionState.NoAction);
  701. }
  702. }
  703. }
  704. isActionExecutionPhaseActive = false;
  705. BattleUIManager.Instance.SetButtonsInteractable(true);
  706. }
  707. private IEnumerator MovementPhaseWithTargetTracking(Dictionary<GameObject, GameObject> allActions, Dictionary<GameObject, Vector3> movementActions, float movementDuration)
  708. {
  709. float elapsedTime = 0f;
  710. // Store witch agents are still moving (not in attack range)
  711. Dictionary<NavMeshAgent, GameObject> activeMovements = new Dictionary<NavMeshAgent, GameObject>();
  712. Dictionary<NavMeshAgent, float> agentAttackRanges = new Dictionary<NavMeshAgent, float>();
  713. // Initialize active movements for attack actions
  714. foreach (var action in allActions)
  715. {
  716. GameObject actor = action.Key;
  717. GameObject target = action.Value;
  718. if (actor == null || target == null) continue;
  719. NavMeshAgent agent = actor.GetComponent<NavMeshAgent>();
  720. if (agent != null && agent.enabled)
  721. {
  722. // Get the character's attack range
  723. Character character = actor.GetComponent<Character>();
  724. float attackRange = character != null ? character.GetAttackRange() : 2.0f;
  725. // Configure movement speed based on character's MovementSpeed stat
  726. if (character != null)
  727. {
  728. // Convert character movement speed to NavMeshAgent speed (HALVED for better gameplay)
  729. // Base conversion: MovementSpeed 10 = 1.75 units/sec, scale from there
  730. agent.speed = (character.MovementSpeed / 10f) * 1.75f;
  731. // Set high acceleration to reach max speed quickly
  732. agent.acceleration = agent.speed * 3.0f; // Reach max speed in ~0.33 seconds
  733. }
  734. else
  735. {
  736. agent.speed = 1.75f; // Default speed if no character component (halved)
  737. agent.acceleration = 5.25f; // Default acceleration (halved)
  738. }
  739. // Configure agent for proper pathfinding around obstacles
  740. agent.obstacleAvoidanceType = ObstacleAvoidanceType.HighQualityObstacleAvoidance;
  741. agent.avoidancePriority = UnityEngine.Random.Range(0, 100); // Random priority to avoid clustering
  742. activeMovements[agent] = target;
  743. agentAttackRanges[agent] = attackRange;
  744. }
  745. }
  746. // Initialize active movements for pure movement actions
  747. foreach (var movement in movementActions)
  748. {
  749. GameObject actor = movement.Key;
  750. Vector3 targetPosition = movement.Value;
  751. if (actor == null) continue;
  752. NavMeshAgent agent = actor.GetComponent<NavMeshAgent>();
  753. if (agent != null && agent.enabled)
  754. {
  755. // For movement actions, use a small stopping distance to get closer
  756. float arrivalRange = 1.2f;
  757. // Configure movement speed based on character's MovementSpeed stat
  758. Character character = actor.GetComponent<Character>();
  759. if (character != null)
  760. {
  761. // Convert character movement speed to NavMeshAgent speed (HALVED for better gameplay)
  762. // Base conversion: MovementSpeed 10 = 1.75 units/sec, scale from there
  763. agent.speed = (character.MovementSpeed / 10f) * 1.75f;
  764. // Set high acceleration to reach max speed quickly
  765. agent.acceleration = agent.speed * 3.0f; // Reach max speed in ~0.33 seconds
  766. }
  767. else
  768. {
  769. agent.speed = 1.75f; // Default speed if no character component (halved)
  770. agent.acceleration = 5.25f; // Default acceleration (halved)
  771. }
  772. // Configure agent for proper pathfinding around obstacles
  773. agent.obstacleAvoidanceType = ObstacleAvoidanceType.HighQualityObstacleAvoidance;
  774. agent.avoidancePriority = UnityEngine.Random.Range(0, 100);
  775. agent.stoppingDistance = 0.1f; // Get very close to the target
  776. // Create a dummy target GameObject at the position for consistency with the tracking system
  777. GameObject dummyTarget = new GameObject("MovementTarget");
  778. dummyTarget.transform.position = targetPosition;
  779. activeMovements[agent] = dummyTarget;
  780. agentAttackRanges[agent] = arrivalRange;
  781. }
  782. }
  783. Debug.Log($"🏃 MOVEMENT PHASE START - TimeScale={Time.timeScale}, ActiveMovements={activeMovements.Count}, Duration={movementDuration}");
  784. while (elapsedTime < movementDuration && Time.timeScale > 0 && activeMovements.Count > 0)
  785. {
  786. var agentsToRemove = new List<NavMeshAgent>();
  787. foreach (var movement in activeMovements)
  788. {
  789. NavMeshAgent agent = movement.Key;
  790. GameObject target = movement.Value;
  791. float attackRange = agentAttackRanges[agent];
  792. if (agent == null || target == null || agent.gameObject == null)
  793. {
  794. agentsToRemove.Add(agent);
  795. continue;
  796. }
  797. float distanceToTarget = Vector3.Distance(agent.transform.position, target.transform.position);
  798. // Debug velocity and speed every 10 frames to avoid spam
  799. if (Time.frameCount % 10 == 0)
  800. {
  801. Character character = agent.GetComponent<Character>();
  802. string charName = character != null ? character.CharacterName : agent.gameObject.name;
  803. Debug.Log($"🏃‍♂️ VELOCITY - {charName}: Speed={agent.speed:F1}, Velocity={agent.velocity.magnitude:F2}, Distance={distanceToTarget:F1}");
  804. }
  805. if (distanceToTarget <= attackRange)
  806. {
  807. agent.isStopped = true;
  808. agent.velocity = Vector3.zero;
  809. agentsToRemove.Add(agent);
  810. // If this is a movement target (dummy), check if we should reset the action
  811. if (target.name == "MovementTarget")
  812. {
  813. Character character = agent.GetComponent<Character>();
  814. if (character != null && character.actionData.targetPosition != Vector3.zero)
  815. {
  816. character.actionData.Reset();
  817. character.SetVisualState(ActionDecisionState.NoAction);
  818. }
  819. }
  820. }
  821. else if (!agent.isStopped)
  822. {
  823. // For movement targets, go directly to the position
  824. if (target.name == "MovementTarget")
  825. {
  826. agent.SetDestination(target.transform.position);
  827. // Check if agent has reached destination or is very close but stopped moving
  828. if (agent.pathStatus == NavMeshPathStatus.PathComplete &&
  829. (!agent.hasPath || agent.remainingDistance < 0.1f))
  830. {
  831. Character character = agent.GetComponent<Character>();
  832. if (character != null)
  833. {
  834. Vector3 actorPos = agent.transform.position;
  835. Vector3 targetPos = character.actionData.targetPosition;
  836. Vector2 actorPos2D = new Vector2(actorPos.x, actorPos.z);
  837. Vector2 targetPos2D = new Vector2(targetPos.x, targetPos.z);
  838. float horizontalDistance = Vector2.Distance(actorPos2D, targetPos2D);
  839. if (horizontalDistance <= 1.2f)
  840. {
  841. agent.isStopped = true;
  842. agentsToRemove.Add(agent);
  843. character.actionData.Reset();
  844. character.SetVisualState(ActionDecisionState.NoAction);
  845. }
  846. }
  847. }
  848. }
  849. else
  850. {
  851. // Update destination to track moving target, but stop just outside attack range
  852. Vector3 directionToTarget = (target.transform.position - agent.transform.position).normalized;
  853. Vector3 stoppingPosition = target.transform.position - directionToTarget * (attackRange * 0.9f);
  854. agent.SetDestination(stoppingPosition);
  855. }
  856. // Check if agent is stuck or can't reach destination
  857. if (agent.pathStatus == NavMeshPathStatus.PathInvalid)
  858. {
  859. Debug.LogWarning($"{agent.gameObject.name} cannot find path to {target.name}");
  860. agent.SetDestination(target.transform.position);
  861. }
  862. }
  863. }
  864. foreach (var agent in agentsToRemove)
  865. {
  866. activeMovements.Remove(agent);
  867. agentAttackRanges.Remove(agent);
  868. }
  869. yield return null; // wait one frame
  870. elapsedTime += Time.deltaTime;
  871. }
  872. // Stop any remaining moving agents and clean up dummy targets
  873. foreach (var movement in activeMovements)
  874. {
  875. if (movement.Key != null && movement.Key.enabled)
  876. {
  877. movement.Key.isStopped = true;
  878. movement.Key.velocity = Vector3.zero;
  879. }
  880. // Clean up dummy movement targets
  881. if (movement.Value != null && movement.Value.name == "MovementTarget")
  882. {
  883. Destroy(movement.Value);
  884. }
  885. }
  886. }
  887. public void AdvanceAction()
  888. {
  889. // Hide action lines when advancing
  890. if (playerDecisionController != null)
  891. {
  892. playerDecisionController.HideActiveActionLines();
  893. }
  894. if (waitingForAdvanceInput)
  895. {
  896. waitingForAdvanceInput = false;
  897. }
  898. else if (Time.timeScale == 0 && !isActionExecutionPhaseActive)
  899. {
  900. ResumeGame();
  901. }
  902. else
  903. {
  904. }
  905. }
  906. public void PauseGame()
  907. {
  908. Time.timeScale = 0f; // Pause the game
  909. BattleUIManager.Instance.SetButtonsInteractable(true);
  910. }
  911. public void ResumeGame()
  912. {
  913. Time.timeScale = 1f; // Resume the game
  914. }
  915. private void EnemiesDecideAction()
  916. {
  917. enemySelectedTargets.Clear();
  918. foreach (var enemy in enemyCharacters)
  919. {
  920. if (enemy == null)
  921. {
  922. Debug.LogWarning("Found null enemy in enemyCharacters list");
  923. continue;
  924. }
  925. if (playerCharacters.Count == 0)
  926. {
  927. Debug.LogWarning("No player characters available for enemies to target");
  928. continue;
  929. }
  930. // Logic for enemy action decision
  931. GameObject closestPlayer = null;
  932. float minDistance = float.MaxValue;
  933. List<GameObject> alivePlayers = playerCharacters.Where(player => !player.GetComponent<Character>().IsDead).ToList();
  934. foreach (var player in alivePlayers)
  935. {
  936. if (player == null) continue; // Safety check
  937. float distance = Vector3.Distance(enemy.transform.position, player.transform.position);
  938. if (distance < minDistance)
  939. {
  940. minDistance = distance;
  941. closestPlayer = player;
  942. }
  943. }
  944. if (closestPlayer != null)
  945. {
  946. // Set the enemy's action data to attack the target
  947. Character enemyCharacter = enemy.GetComponent<Character>();
  948. if (enemyCharacter != null)
  949. {
  950. enemyCharacter.actionData.SetAttackTarget(closestPlayer);
  951. }
  952. enemySelectedTargets[enemy] = closestPlayer; // Assign the closest player as the target
  953. }
  954. else
  955. {
  956. Debug.LogWarning($"{enemy.name} could not find a valid target");
  957. }
  958. enemy.GetComponent<Character>().SetVisualState(ActionDecisionState.EnemyAction);
  959. }
  960. }
  961. private void CheckAndResetCompletedMovements()
  962. {
  963. foreach (GameObject playerGO in playerCharacters)
  964. {
  965. Character character = playerGO.GetComponent<Character>();
  966. if (character != null && character.actionData.targetPosition != Vector3.zero && character.actionData.targetEnemy == null)
  967. {
  968. // This is a movement action, check if completed using horizontal distance only
  969. Vector3 playerPos = playerGO.transform.position;
  970. Vector3 targetPos = character.actionData.targetPosition;
  971. // Use only X and Z coordinates (ignore Y differences)
  972. Vector2 playerPos2D = new Vector2(playerPos.x, playerPos.z);
  973. Vector2 targetPos2D = new Vector2(targetPos.x, targetPos.z);
  974. float horizontalDistance = Vector2.Distance(playerPos2D, targetPos2D);
  975. if (horizontalDistance <= 1.2f) // Threshold for "close enough"
  976. {
  977. character.actionData.Reset();
  978. character.SetVisualState(ActionDecisionState.NoAction);
  979. }
  980. }
  981. }
  982. }
  983. }