SimpleTeamPlacement.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. /// <summary>
  5. /// Simple standalone team placement script that randomly places the team on a settlement
  6. /// and creates a visible marker in front of the map.
  7. /// </summary>
  8. public class SimpleTeamPlacement : MonoBehaviour
  9. {
  10. [Header("Team Marker Settings")]
  11. public GameObject teamMarkerPrefab;
  12. public Material teamMarkerMaterial;
  13. [Range(0.5f, 3f)]
  14. public float markerSize = 1.5f;
  15. [Range(-5f, 5f)]
  16. public float markerHeight = 0.5f; // Y coordinate height above map tiles
  17. public Color markerColor = Color.green;
  18. [Header("Animation Settings")]
  19. public bool enableBlinking = true;
  20. [Range(0.1f, 2f)]
  21. public float blinkSpeed = 0.5f;
  22. // Private variables
  23. private GameObject teamMarkerInstance;
  24. private Vector2Int currentTeamPosition;
  25. private bool isTeamPositionSet = false;
  26. private bool isBlinking = false;
  27. private MapMaker2 mapMaker;
  28. public static SimpleTeamPlacement Instance { get; private set; }
  29. /// <summary>
  30. /// Gets the current team marker GameObject instance
  31. /// </summary>
  32. public GameObject TeamMarkerInstance => teamMarkerInstance;
  33. /// <summary>
  34. /// Gets the world position of the team marker
  35. /// </summary>
  36. public Vector3 TeamMarkerWorldPosition
  37. {
  38. get
  39. {
  40. if (teamMarkerInstance != null)
  41. return teamMarkerInstance.transform.position;
  42. return Vector3.zero;
  43. }
  44. }
  45. void Awake()
  46. {
  47. if (Instance == null)
  48. {
  49. Instance = this;
  50. }
  51. else
  52. {
  53. Debug.LogWarning("Multiple SimpleTeamPlacement instances found. Destroying this one.");
  54. Destroy(gameObject);
  55. return;
  56. }
  57. }
  58. void Start()
  59. {
  60. // Find MapMaker2
  61. mapMaker = FindFirstObjectByType<MapMaker2>();
  62. if (mapMaker == null)
  63. {
  64. return;
  65. }
  66. // Wait a bit for map generation, then place team
  67. StartCoroutine(WaitAndPlaceTeam());
  68. }
  69. void Update()
  70. {
  71. // Debug keys
  72. if (Input.GetKeyDown(KeyCode.R))
  73. {
  74. RandomlyPlaceTeam();
  75. }
  76. if (Input.GetKeyDown(KeyCode.M))
  77. {
  78. ShowMarkerInfo();
  79. }
  80. // Debug key to check saved positions
  81. if (Input.GetKeyDown(KeyCode.P))
  82. {
  83. DebugSavedPositions();
  84. }
  85. // Travel system integration - allow clicking on map to plan travel
  86. if (Input.GetKeyDown(KeyCode.T))
  87. {
  88. ShowTravelInfo();
  89. }
  90. }
  91. private IEnumerator WaitAndPlaceTeam()
  92. {
  93. // Wait for map generation
  94. yield return new WaitForSeconds(1.5f);
  95. // Check if this is a new game that should force random placement
  96. // First ensure GameStateManager exists, create it if needed
  97. if (GameStateManager.Instance == null)
  98. {
  99. GameObject gameStateObj = new GameObject("GameStateManager");
  100. gameStateObj.AddComponent<GameStateManager>();
  101. // Wait a frame for the GameStateManager to initialize
  102. yield return null;
  103. }
  104. bool isNewGame = GameStateManager.Instance?.IsNewGameForceRandom() ?? false;
  105. // ALWAYS show new game detection debug logs (even if showDebugLogs is false)
  106. if (isNewGame)
  107. {
  108. RandomlyPlaceTeam();
  109. // Clear the new game flag after placement
  110. GameStateManager.Instance?.ClearNewGameFlag();
  111. yield break;
  112. }
  113. // Try multiple times to load saved position (in case MapMaker2 isn't ready yet)
  114. int attempts = 0;
  115. const int maxAttempts = 5;
  116. while (attempts < maxAttempts)
  117. {
  118. attempts++;
  119. // Try to load saved position first
  120. if (TryLoadSavedPosition())
  121. {
  122. yield break; // Exit successfully
  123. }
  124. // If failed and MapMaker seed is still 0, wait a bit more
  125. if (mapMaker?.seed == 0 && attempts < maxAttempts)
  126. {
  127. yield return new WaitForSeconds(0.5f);
  128. }
  129. else
  130. {
  131. break; // Either loaded successfully or MapMaker is ready but no saved position
  132. }
  133. }
  134. // No saved position or invalid, place randomly
  135. RandomlyPlaceTeam();
  136. }
  137. private bool TryLoadSavedPosition()
  138. {
  139. // Get the current map seed to make position specific to this map
  140. int currentSeed = mapMaker?.seed ?? 0;
  141. string positionKey = $"TeamPosition_{currentSeed}";
  142. if (currentSeed == 0)
  143. {
  144. return false;
  145. }
  146. if (!PlayerPrefs.HasKey($"{positionKey}_X") || !PlayerPrefs.HasKey($"{positionKey}_Y"))
  147. {
  148. return false;
  149. }
  150. Vector2Int savedPosition = new Vector2Int(
  151. PlayerPrefs.GetInt($"{positionKey}_X"),
  152. PlayerPrefs.GetInt($"{positionKey}_Y")
  153. );
  154. // Verify position is still valid (any valid map position, not just settlements)
  155. if (IsValidMapPosition(savedPosition))
  156. {
  157. PlaceTeamAt(savedPosition);
  158. return true;
  159. }
  160. return false;
  161. }
  162. public void RandomlyPlaceTeam()
  163. {
  164. if (mapMaker?.GetMapData() == null)
  165. {
  166. return;
  167. }
  168. // For new games, ensure we're using the current random state for truly random placement
  169. bool isNewGame = GameStateManager.Instance?.IsNewGameForceRandom() ?? false;
  170. var mapData = mapMaker.GetMapData();
  171. var allSettlements = new List<Settlement>();
  172. // Combine towns and villages into one list for random selection
  173. allSettlements.AddRange(mapData.GetTowns());
  174. allSettlements.AddRange(mapData.GetVillages());
  175. if (allSettlements.Count == 0)
  176. {
  177. return;
  178. }
  179. // Randomly select a settlement
  180. int randomIndex = Random.Range(0, allSettlements.Count);
  181. Settlement selectedSettlement = allSettlements[randomIndex];
  182. PlaceTeamAt(selectedSettlement.position);
  183. }
  184. public void PlaceTeamAt(Vector2Int position)
  185. {
  186. currentTeamPosition = position;
  187. isTeamPositionSet = true;
  188. // Save position with map seed for persistence
  189. int currentSeed = mapMaker?.seed ?? 0;
  190. string positionKey = $"TeamPosition_{currentSeed}";
  191. bool isNewGame = GameStateManager.Instance?.IsNewGameForceRandom() ?? false;
  192. PlayerPrefs.SetInt($"{positionKey}_X", position.x);
  193. PlayerPrefs.SetInt($"{positionKey}_Y", position.y);
  194. PlayerPrefs.Save();
  195. // Create/update visual marker
  196. CreateTeamMarker();
  197. // Notify MapMaker2 of position change for event-driven exploration
  198. if (mapMaker != null)
  199. {
  200. mapMaker.OnTeamPositionChanged(position);
  201. // Set TeamMarker reference in SettlementInteractionManager
  202. var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
  203. if (settlementManager != null)
  204. {
  205. settlementManager.SetTeamMarker(teamMarkerInstance.transform);
  206. }
  207. else
  208. {
  209. Debug.LogWarning("[SimpleTeamPlacement] SettlementInteractionManager not found!");
  210. }
  211. }
  212. }
  213. /// <summary>
  214. /// Cleans up position data for old map seeds (optional maintenance)
  215. /// </summary>
  216. public void CleanupOldPositionData()
  217. {
  218. int currentSeed = mapMaker?.seed ?? 0;
  219. int cleanedCount = 0;
  220. // This is a simple cleanup - in a real game you might want more sophisticated management
  221. for (int i = 0; i < 10; i++) // Check last 10 potential seeds for cleanup
  222. {
  223. int testSeed = currentSeed - i;
  224. if (testSeed != currentSeed && testSeed > 0)
  225. {
  226. string positionKey = $"TeamPosition_{testSeed}";
  227. if (PlayerPrefs.HasKey($"{positionKey}_X"))
  228. {
  229. PlayerPrefs.DeleteKey($"{positionKey}_X");
  230. PlayerPrefs.DeleteKey($"{positionKey}_Y");
  231. cleanedCount++;
  232. }
  233. }
  234. }
  235. }
  236. /// <summary>
  237. /// Debug method to check what positions are saved in PlayerPrefs
  238. /// </summary>
  239. private void DebugSavedPositions()
  240. {
  241. int currentSeed = mapMaker?.seed ?? 0;
  242. // Check current seed position
  243. string currentKey = $"TeamPosition_{currentSeed}";
  244. bool hasCurrentPosition = PlayerPrefs.HasKey($"{currentKey}_X") && PlayerPrefs.HasKey($"{currentKey}_Y");
  245. if (hasCurrentPosition)
  246. {
  247. Vector2Int currentPos = new Vector2Int(
  248. PlayerPrefs.GetInt($"{currentKey}_X"),
  249. PlayerPrefs.GetInt($"{currentKey}_Y")
  250. );
  251. }
  252. else
  253. {
  254. }
  255. // Check for other potential seeds (common ones)
  256. int[] testSeeds = { 0, 12345, 1000, 5000, 9999 };
  257. foreach (int testSeed in testSeeds)
  258. {
  259. if (testSeed == currentSeed) continue; // Already checked
  260. string testKey = $"TeamPosition_{testSeed}";
  261. if (PlayerPrefs.HasKey($"{testKey}_X") && PlayerPrefs.HasKey($"{testKey}_Y"))
  262. {
  263. Vector2Int testPos = new Vector2Int(
  264. PlayerPrefs.GetInt($"{testKey}_X"),
  265. PlayerPrefs.GetInt($"{testKey}_Y")
  266. );
  267. }
  268. }
  269. }
  270. private void CreateTeamMarker()
  271. {
  272. // Stop any existing blinking first
  273. if (isBlinking)
  274. {
  275. StopAllCoroutines(); // This will stop the BlinkMarker coroutine
  276. isBlinking = false;
  277. }
  278. // Remove existing marker
  279. if (teamMarkerInstance != null)
  280. {
  281. DestroyImmediate(teamMarkerInstance);
  282. }
  283. // Create new marker
  284. if (teamMarkerPrefab != null)
  285. {
  286. teamMarkerInstance = Instantiate(teamMarkerPrefab);
  287. }
  288. else
  289. {
  290. // Create simple sphere marker
  291. teamMarkerInstance = GameObject.CreatePrimitive(PrimitiveType.Sphere);
  292. teamMarkerInstance.transform.localScale = Vector3.one * markerSize;
  293. teamMarkerInstance.tag = "Player";
  294. }
  295. // Position marker
  296. PositionMarker();
  297. // Apply material/color
  298. ApplyMarkerMaterial();
  299. // Set name
  300. teamMarkerInstance.name = "TeamMarker";
  301. // Start blinking if enabled
  302. if (enableBlinking)
  303. {
  304. StartBlinking();
  305. }
  306. // Notify camera to center on the newly created team marker
  307. var cameraController = FindFirstObjectByType<MMCameraController>();
  308. if (cameraController != null)
  309. {
  310. cameraController.OnTeamMarkerCreated();
  311. }
  312. }
  313. /// <summary>
  314. /// Get current team position
  315. /// </summary>
  316. public Vector2Int GetCurrentTeamPosition()
  317. {
  318. return currentTeamPosition;
  319. }
  320. /// <summary>
  321. /// Update team marker position when map coordinates change (called by exploration system)
  322. /// </summary>
  323. public void UpdateMarkerAfterMapChange(Vector2Int newVisiblePosition)
  324. {
  325. if (!isTeamPositionSet || teamMarkerInstance == null)
  326. {
  327. return;
  328. }
  329. // Store the world position before updating coordinates
  330. Vector3 currentWorldPos = teamMarkerInstance.transform.position;
  331. // Update the current team position to the new visible coordinates
  332. Vector2Int oldPosition = currentTeamPosition;
  333. currentTeamPosition = newVisiblePosition;
  334. // Reposition the marker to maintain world position consistency
  335. PositionMarker();
  336. }
  337. private void PositionMarker()
  338. {
  339. // Get tile size from MapVisualizer
  340. float tileSize = 1f;
  341. if (mapMaker?.mapVisualizer != null)
  342. {
  343. tileSize = mapMaker.mapVisualizer.tileSize;
  344. }
  345. // Calculate world position:
  346. // In exploration mode, we need to convert exploration coordinates to full map coordinates for world positioning
  347. Vector2Int worldCoordinates = currentTeamPosition;
  348. // Check if we're using exploration system
  349. if (mapMaker != null && mapMaker.useExplorationSystem)
  350. {
  351. var explorationManager = mapMaker.GetExplorationManager();
  352. if (explorationManager != null)
  353. {
  354. // Use exploration manager to convert coordinates properly
  355. Vector3 correctWorldPos = explorationManager.ConvertExplorationToWorldCoordinates(currentTeamPosition);
  356. teamMarkerInstance.transform.position = new Vector3(
  357. correctWorldPos.x,
  358. markerHeight, // Y coordinate height above map tiles
  359. correctWorldPos.z // Use Z coordinate for map Y position
  360. );
  361. return;
  362. }
  363. }
  364. // Fallback for non-exploration mode: use direct coordinate mapping
  365. Vector3 worldPosition = new Vector3(
  366. worldCoordinates.x * tileSize,
  367. markerHeight, // Y coordinate height above map tiles
  368. worldCoordinates.y * tileSize // Map Y becomes world Z for top-down view
  369. );
  370. teamMarkerInstance.transform.position = worldPosition;
  371. }
  372. private void ApplyMarkerMaterial()
  373. {
  374. Renderer renderer = teamMarkerInstance.GetComponent<Renderer>();
  375. if (renderer == null) return;
  376. if (teamMarkerMaterial != null)
  377. {
  378. renderer.material = teamMarkerMaterial;
  379. }
  380. else
  381. {
  382. // Create simple colored material using URP shaders first
  383. Shader shader = null;
  384. // Try URP shaders first
  385. shader = Shader.Find("Universal Render Pipeline/Lit");
  386. if (shader == null)
  387. shader = Shader.Find("Universal Render Pipeline/Simple Lit");
  388. if (shader == null)
  389. shader = Shader.Find("Universal Render Pipeline/Unlit");
  390. // Fallback to built-in shaders
  391. if (shader == null)
  392. shader = Shader.Find("Standard");
  393. if (shader == null)
  394. shader = Shader.Find("Legacy Shaders/Diffuse");
  395. if (shader == null)
  396. shader = Shader.Find("Unlit/Color");
  397. // Last resort fallback
  398. if (shader == null)
  399. {
  400. return;
  401. }
  402. Material material = new Material(shader);
  403. // Set base color (works for both URP and built-in)
  404. if (material.HasProperty("_BaseColor"))
  405. {
  406. material.SetColor("_BaseColor", markerColor); // URP property
  407. }
  408. else if (material.HasProperty("_Color"))
  409. {
  410. material.SetColor("_Color", markerColor); // Built-in property
  411. }
  412. material.color = markerColor; // Fallback
  413. // Add emission for better visibility
  414. if (material.HasProperty("_EmissionColor"))
  415. {
  416. material.EnableKeyword("_EMISSION");
  417. material.SetColor("_EmissionColor", markerColor * 0.3f);
  418. }
  419. renderer.material = material;
  420. }
  421. }
  422. private void StartBlinking()
  423. {
  424. if (!isBlinking)
  425. {
  426. StartCoroutine(BlinkMarker());
  427. }
  428. else
  429. {
  430. // Force restart blinking as a fallback
  431. StopAllCoroutines();
  432. isBlinking = false;
  433. StartCoroutine(BlinkMarker());
  434. }
  435. }
  436. private IEnumerator BlinkMarker()
  437. {
  438. isBlinking = true;
  439. Renderer markerRenderer = teamMarkerInstance?.GetComponent<Renderer>();
  440. if (markerRenderer == null)
  441. {
  442. isBlinking = false;
  443. yield break;
  444. }
  445. // Capture the enableBlinking state at start to avoid timing issues
  446. bool shouldBlink = enableBlinking;
  447. int blinkCount = 0;
  448. while (teamMarkerInstance != null && markerRenderer != null && shouldBlink)
  449. {
  450. // Hide marker
  451. markerRenderer.enabled = false;
  452. yield return new WaitForSeconds(blinkSpeed);
  453. // Show marker
  454. if (markerRenderer != null && teamMarkerInstance != null)
  455. {
  456. markerRenderer.enabled = true;
  457. yield return new WaitForSeconds(blinkSpeed);
  458. blinkCount++;
  459. }
  460. else
  461. {
  462. break;
  463. }
  464. // Re-check enableBlinking periodically (every 10 blinks) in case user changes it
  465. if (blinkCount % 10 == 0)
  466. {
  467. shouldBlink = enableBlinking;
  468. }
  469. }
  470. isBlinking = false;
  471. }
  472. private bool IsValidSettlementPosition(Vector2Int position)
  473. {
  474. if (mapMaker?.GetMapData() == null) return false;
  475. var mapData = mapMaker.GetMapData();
  476. if (!mapData.IsValidPosition(position.x, position.y)) return false;
  477. // Check if position has a settlement
  478. foreach (var town in mapData.GetTowns())
  479. {
  480. if (town.position == position) return true;
  481. }
  482. foreach (var village in mapData.GetVillages())
  483. {
  484. if (village.position == position) return true;
  485. }
  486. return false;
  487. }
  488. /// <summary>
  489. /// Checks if a position is valid for team placement (any valid map position)
  490. /// Used for persistent positioning - team can be anywhere on the map
  491. /// </summary>
  492. private bool IsValidMapPosition(Vector2Int position)
  493. {
  494. if (mapMaker?.GetMapData() == null)
  495. {
  496. return false;
  497. }
  498. var mapData = mapMaker.GetMapData();
  499. return mapData.IsValidPosition(position.x, position.y);
  500. }
  501. private void ShowMarkerInfo()
  502. {
  503. if (teamMarkerInstance == null)
  504. {
  505. return;
  506. }
  507. }
  508. private void ShowTravelInfo()
  509. {
  510. var travelSystem = TeamTravelSystem.Instance;
  511. if (travelSystem != null)
  512. {
  513. }
  514. else
  515. {
  516. }
  517. }
  518. // Public methods for external control
  519. public Vector2Int GetTeamPosition() => currentTeamPosition;
  520. public bool IsTeamPlaced() => isTeamPositionSet;
  521. public GameObject GetTeamMarker() => teamMarkerInstance;
  522. [ContextMenu("Randomly Place Team")]
  523. public void ContextRandomlyPlaceTeam()
  524. {
  525. RandomlyPlaceTeam();
  526. }
  527. [ContextMenu("Show Marker Info")]
  528. public void ContextShowMarkerInfo()
  529. {
  530. ShowMarkerInfo();
  531. }
  532. [ContextMenu("Force New Game Random Placement")]
  533. public void ContextForceNewGamePlacement()
  534. {
  535. // Temporarily set new game flag for testing
  536. if (GameStateManager.Instance != null)
  537. {
  538. GameStateManager.Instance.isNewGame = true;
  539. }
  540. RandomlyPlaceTeam();
  541. // Clear the flag after testing
  542. GameStateManager.Instance?.ClearNewGameFlag();
  543. }
  544. }