SimpleTeamPlacement.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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. }
  202. }
  203. /// <summary>
  204. /// Cleans up position data for old map seeds (optional maintenance)
  205. /// </summary>
  206. public void CleanupOldPositionData()
  207. {
  208. int currentSeed = mapMaker?.seed ?? 0;
  209. int cleanedCount = 0;
  210. // This is a simple cleanup - in a real game you might want more sophisticated management
  211. for (int i = 0; i < 10; i++) // Check last 10 potential seeds for cleanup
  212. {
  213. int testSeed = currentSeed - i;
  214. if (testSeed != currentSeed && testSeed > 0)
  215. {
  216. string positionKey = $"TeamPosition_{testSeed}";
  217. if (PlayerPrefs.HasKey($"{positionKey}_X"))
  218. {
  219. PlayerPrefs.DeleteKey($"{positionKey}_X");
  220. PlayerPrefs.DeleteKey($"{positionKey}_Y");
  221. cleanedCount++;
  222. }
  223. }
  224. }
  225. }
  226. /// <summary>
  227. /// Debug method to check what positions are saved in PlayerPrefs
  228. /// </summary>
  229. private void DebugSavedPositions()
  230. {
  231. int currentSeed = mapMaker?.seed ?? 0;
  232. // Check current seed position
  233. string currentKey = $"TeamPosition_{currentSeed}";
  234. bool hasCurrentPosition = PlayerPrefs.HasKey($"{currentKey}_X") && PlayerPrefs.HasKey($"{currentKey}_Y");
  235. if (hasCurrentPosition)
  236. {
  237. Vector2Int currentPos = new Vector2Int(
  238. PlayerPrefs.GetInt($"{currentKey}_X"),
  239. PlayerPrefs.GetInt($"{currentKey}_Y")
  240. );
  241. }
  242. else
  243. {
  244. }
  245. // Check for other potential seeds (common ones)
  246. int[] testSeeds = { 0, 12345, 1000, 5000, 9999 };
  247. foreach (int testSeed in testSeeds)
  248. {
  249. if (testSeed == currentSeed) continue; // Already checked
  250. string testKey = $"TeamPosition_{testSeed}";
  251. if (PlayerPrefs.HasKey($"{testKey}_X") && PlayerPrefs.HasKey($"{testKey}_Y"))
  252. {
  253. Vector2Int testPos = new Vector2Int(
  254. PlayerPrefs.GetInt($"{testKey}_X"),
  255. PlayerPrefs.GetInt($"{testKey}_Y")
  256. );
  257. }
  258. }
  259. }
  260. private void CreateTeamMarker()
  261. {
  262. // Stop any existing blinking first
  263. if (isBlinking)
  264. {
  265. StopAllCoroutines(); // This will stop the BlinkMarker coroutine
  266. isBlinking = false;
  267. }
  268. // Remove existing marker
  269. if (teamMarkerInstance != null)
  270. {
  271. DestroyImmediate(teamMarkerInstance);
  272. }
  273. // Create new marker
  274. if (teamMarkerPrefab != null)
  275. {
  276. teamMarkerInstance = Instantiate(teamMarkerPrefab);
  277. }
  278. else
  279. {
  280. // Create simple sphere marker
  281. teamMarkerInstance = GameObject.CreatePrimitive(PrimitiveType.Sphere);
  282. teamMarkerInstance.transform.localScale = Vector3.one * markerSize;
  283. teamMarkerInstance.tag = "Player";
  284. }
  285. // Position marker
  286. PositionMarker();
  287. // Apply material/color
  288. ApplyMarkerMaterial();
  289. // Set name
  290. teamMarkerInstance.name = "TeamMarker";
  291. // Start blinking if enabled
  292. if (enableBlinking)
  293. {
  294. StartBlinking();
  295. }
  296. // Notify camera to center on the newly created team marker
  297. var cameraController = FindFirstObjectByType<MMCameraController>();
  298. if (cameraController != null)
  299. {
  300. cameraController.OnTeamMarkerCreated();
  301. }
  302. }
  303. /// <summary>
  304. /// Get current team position
  305. /// </summary>
  306. public Vector2Int GetCurrentTeamPosition()
  307. {
  308. return currentTeamPosition;
  309. }
  310. /// <summary>
  311. /// Update team marker position when map coordinates change (called by exploration system)
  312. /// </summary>
  313. public void UpdateMarkerAfterMapChange(Vector2Int newVisiblePosition)
  314. {
  315. if (!isTeamPositionSet || teamMarkerInstance == null)
  316. {
  317. return;
  318. }
  319. // Store the world position before updating coordinates
  320. Vector3 currentWorldPos = teamMarkerInstance.transform.position;
  321. // Update the current team position to the new visible coordinates
  322. Vector2Int oldPosition = currentTeamPosition;
  323. currentTeamPosition = newVisiblePosition;
  324. // Reposition the marker to maintain world position consistency
  325. PositionMarker();
  326. }
  327. private void PositionMarker()
  328. {
  329. // Get tile size from MapVisualizer
  330. float tileSize = 1f;
  331. if (mapMaker?.mapVisualizer != null)
  332. {
  333. tileSize = mapMaker.mapVisualizer.tileSize;
  334. }
  335. // Calculate world position:
  336. // In exploration mode, we need to convert exploration coordinates to full map coordinates for world positioning
  337. Vector2Int worldCoordinates = currentTeamPosition;
  338. // Check if we're using exploration system
  339. if (mapMaker != null && mapMaker.useExplorationSystem)
  340. {
  341. var explorationManager = mapMaker.GetExplorationManager();
  342. if (explorationManager != null)
  343. {
  344. // Use exploration manager to convert coordinates properly
  345. Vector3 correctWorldPos = explorationManager.ConvertExplorationToWorldCoordinates(currentTeamPosition);
  346. teamMarkerInstance.transform.position = new Vector3(
  347. correctWorldPos.x,
  348. markerHeight, // Y coordinate height above map tiles
  349. correctWorldPos.z // Use Z coordinate for map Y position
  350. );
  351. return;
  352. }
  353. }
  354. // Fallback for non-exploration mode: use direct coordinate mapping
  355. Vector3 worldPosition = new Vector3(
  356. worldCoordinates.x * tileSize,
  357. markerHeight, // Y coordinate height above map tiles
  358. worldCoordinates.y * tileSize // Map Y becomes world Z for top-down view
  359. );
  360. teamMarkerInstance.transform.position = worldPosition;
  361. }
  362. private void ApplyMarkerMaterial()
  363. {
  364. Renderer renderer = teamMarkerInstance.GetComponent<Renderer>();
  365. if (renderer == null) return;
  366. if (teamMarkerMaterial != null)
  367. {
  368. renderer.material = teamMarkerMaterial;
  369. }
  370. else
  371. {
  372. // Create simple colored material using URP shaders first
  373. Shader shader = null;
  374. // Try URP shaders first
  375. shader = Shader.Find("Universal Render Pipeline/Lit");
  376. if (shader == null)
  377. shader = Shader.Find("Universal Render Pipeline/Simple Lit");
  378. if (shader == null)
  379. shader = Shader.Find("Universal Render Pipeline/Unlit");
  380. // Fallback to built-in shaders
  381. if (shader == null)
  382. shader = Shader.Find("Standard");
  383. if (shader == null)
  384. shader = Shader.Find("Legacy Shaders/Diffuse");
  385. if (shader == null)
  386. shader = Shader.Find("Unlit/Color");
  387. // Last resort fallback
  388. if (shader == null)
  389. {
  390. return;
  391. }
  392. Material material = new Material(shader);
  393. // Set base color (works for both URP and built-in)
  394. if (material.HasProperty("_BaseColor"))
  395. {
  396. material.SetColor("_BaseColor", markerColor); // URP property
  397. }
  398. else if (material.HasProperty("_Color"))
  399. {
  400. material.SetColor("_Color", markerColor); // Built-in property
  401. }
  402. material.color = markerColor; // Fallback
  403. // Add emission for better visibility
  404. if (material.HasProperty("_EmissionColor"))
  405. {
  406. material.EnableKeyword("_EMISSION");
  407. material.SetColor("_EmissionColor", markerColor * 0.3f);
  408. }
  409. renderer.material = material;
  410. }
  411. }
  412. private void StartBlinking()
  413. {
  414. if (!isBlinking)
  415. {
  416. StartCoroutine(BlinkMarker());
  417. }
  418. else
  419. {
  420. // Force restart blinking as a fallback
  421. StopAllCoroutines();
  422. isBlinking = false;
  423. StartCoroutine(BlinkMarker());
  424. }
  425. }
  426. private IEnumerator BlinkMarker()
  427. {
  428. isBlinking = true;
  429. Renderer markerRenderer = teamMarkerInstance?.GetComponent<Renderer>();
  430. if (markerRenderer == null)
  431. {
  432. isBlinking = false;
  433. yield break;
  434. }
  435. // Capture the enableBlinking state at start to avoid timing issues
  436. bool shouldBlink = enableBlinking;
  437. int blinkCount = 0;
  438. while (teamMarkerInstance != null && markerRenderer != null && shouldBlink)
  439. {
  440. // Hide marker
  441. markerRenderer.enabled = false;
  442. yield return new WaitForSeconds(blinkSpeed);
  443. // Show marker
  444. if (markerRenderer != null && teamMarkerInstance != null)
  445. {
  446. markerRenderer.enabled = true;
  447. yield return new WaitForSeconds(blinkSpeed);
  448. blinkCount++;
  449. }
  450. else
  451. {
  452. break;
  453. }
  454. // Re-check enableBlinking periodically (every 10 blinks) in case user changes it
  455. if (blinkCount % 10 == 0)
  456. {
  457. shouldBlink = enableBlinking;
  458. }
  459. }
  460. isBlinking = false;
  461. }
  462. private bool IsValidSettlementPosition(Vector2Int position)
  463. {
  464. if (mapMaker?.GetMapData() == null) return false;
  465. var mapData = mapMaker.GetMapData();
  466. if (!mapData.IsValidPosition(position.x, position.y)) return false;
  467. // Check if position has a settlement
  468. foreach (var town in mapData.GetTowns())
  469. {
  470. if (town.position == position) return true;
  471. }
  472. foreach (var village in mapData.GetVillages())
  473. {
  474. if (village.position == position) return true;
  475. }
  476. return false;
  477. }
  478. /// <summary>
  479. /// Checks if a position is valid for team placement (any valid map position)
  480. /// Used for persistent positioning - team can be anywhere on the map
  481. /// </summary>
  482. private bool IsValidMapPosition(Vector2Int position)
  483. {
  484. if (mapMaker?.GetMapData() == null)
  485. {
  486. return false;
  487. }
  488. var mapData = mapMaker.GetMapData();
  489. return mapData.IsValidPosition(position.x, position.y);
  490. }
  491. private void ShowMarkerInfo()
  492. {
  493. if (teamMarkerInstance == null)
  494. {
  495. return;
  496. }
  497. }
  498. private void ShowTravelInfo()
  499. {
  500. var travelSystem = TeamTravelSystem.Instance;
  501. if (travelSystem != null)
  502. {
  503. }
  504. else
  505. {
  506. }
  507. }
  508. // Public methods for external control
  509. public Vector2Int GetTeamPosition() => currentTeamPosition;
  510. public bool IsTeamPlaced() => isTeamPositionSet;
  511. public GameObject GetTeamMarker() => teamMarkerInstance;
  512. [ContextMenu("Randomly Place Team")]
  513. public void ContextRandomlyPlaceTeam()
  514. {
  515. RandomlyPlaceTeam();
  516. }
  517. [ContextMenu("Show Marker Info")]
  518. public void ContextShowMarkerInfo()
  519. {
  520. ShowMarkerInfo();
  521. }
  522. [ContextMenu("Force New Game Random Placement")]
  523. public void ContextForceNewGamePlacement()
  524. {
  525. // Temporarily set new game flag for testing
  526. if (GameStateManager.Instance != null)
  527. {
  528. GameStateManager.Instance.isNewGame = true;
  529. }
  530. RandomlyPlaceTeam();
  531. // Clear the flag after testing
  532. GameStateManager.Instance?.ClearNewGameFlag();
  533. }
  534. }