NewRoomBuilder.cs 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. public class NewRoomBuilder : MonoBehaviour
  4. {
  5. [Header("Prefabs")]
  6. public GameObject wallPrefab;
  7. public GameObject wallPointPrefab;
  8. public GameObject doorOpeningPrefab;
  9. [Header("Settings")]
  10. public float wallHeight = 3f;
  11. public float wallThickness = 0.2f;
  12. public float doorWidth = 1.5f;
  13. public float doorHeight = 2.5f;
  14. public float snapDistance = 1f; // Distance for snapping to existing points
  15. private Camera playerCamera;
  16. private BuildingUIController.BuildingMode currentMode = BuildingUIController.BuildingMode.Normal;
  17. // Wall creation state
  18. private bool isCreatingWall = false;
  19. private Vector3 wallStartPoint;
  20. private GameObject previewWall;
  21. private LineRenderer previewLine;
  22. // Available angles (in degrees)
  23. private readonly float[] snapAngles = { 0f, 45f, 90f, 135f, 180f, 225f, 270f, 315f };
  24. // Wall storage
  25. private List<GameObject> walls = new List<GameObject>();
  26. // Door preview
  27. private GameObject doorPreview;
  28. private GameObject hoveredWall;
  29. // Snap indicators
  30. private GameObject snapIndicator;
  31. private GameObject currentSnapPoint;
  32. private void Start()
  33. {
  34. // Try multiple ways to find the camera
  35. playerCamera = Camera.main;
  36. if (playerCamera == null)
  37. {
  38. playerCamera = FindFirstObjectByType<Camera>();
  39. Debug.LogWarning($"Camera.main was null, found camera: {playerCamera?.name ?? "NONE"}");
  40. }
  41. if (playerCamera == null)
  42. {
  43. Debug.LogError("No camera found! Wall detection will not work.");
  44. }
  45. else
  46. {
  47. Debug.Log($"Using camera: {playerCamera.name} at {playerCamera.transform.position}");
  48. }
  49. CreatePreviewLine();
  50. CreateDoorPreview();
  51. CreateSnapIndicator();
  52. // Ensure we have prefabs
  53. EnsurePrefabsExist();
  54. // Fix any existing walls that might not be tagged properly
  55. FixExistingWallTags();
  56. }
  57. private void FixExistingWallTags()
  58. {
  59. // First, look for walls that are already properly tagged (from InitialRoomSetup)
  60. GameObject[] existingWalls = GameObject.FindGameObjectsWithTag("Wall");
  61. Debug.Log($"Found {existingWalls.Length} objects already tagged as 'Wall'");
  62. foreach (GameObject wall in existingWalls)
  63. {
  64. if (!walls.Contains(wall))
  65. {
  66. walls.Add(wall);
  67. Debug.Log($"Added existing tagged wall to tracking: {wall.name} - Scale: {wall.transform.localScale}");
  68. }
  69. }
  70. // If we found properly tagged walls, we're done
  71. if (existingWalls.Length > 0)
  72. {
  73. Debug.Log($"Successfully found and added {existingWalls.Length} pre-tagged walls from InitialRoomSetup");
  74. return;
  75. }
  76. // Fallback: Look for objects that should be walls but aren't tagged yet
  77. GameObject[] allObjects = FindObjectsByType<GameObject>(FindObjectsSortMode.None);
  78. int fixedWalls = 0;
  79. Debug.Log($"No pre-tagged walls found. Scanning {allObjects.Length} objects for potential walls...");
  80. foreach (GameObject obj in allObjects)
  81. {
  82. // Skip door components and other non-wall objects
  83. if (obj.name.Contains("Post") || obj.name.Contains("Beam") || obj.name.Contains("Door") ||
  84. obj.name.Contains("Mat") || obj.name.Contains("Entrance") || obj.name.Contains("Frame"))
  85. {
  86. continue;
  87. }
  88. // Look for specific wall naming patterns from InitialRoomSetup
  89. bool isInitialRoomWall = obj.name.Contains("North Wall") || obj.name.Contains("South Wall") ||
  90. obj.name.Contains("East Wall") || obj.name.Contains("West Wall");
  91. // Also check for other wall patterns
  92. bool isWallObject = obj.name.Contains("Wall") ||
  93. obj.name.Contains("wall") ||
  94. obj.name.StartsWith("Room") ||
  95. obj.name.Contains("Interior");
  96. if ((isInitialRoomWall || isWallObject) && !obj.CompareTag("Wall"))
  97. {
  98. // Additional check: make sure it has a collider (walls should have colliders)
  99. if (obj.GetComponent<Collider>() != null || obj.GetComponentInChildren<Collider>() != null)
  100. {
  101. Debug.Log($"Found untagged wall: {obj.name} - Scale: {obj.transform.localScale}, Position: {obj.transform.position}");
  102. obj.tag = "Wall";
  103. fixedWalls++;
  104. Debug.Log($"Fixed wall tag for: {obj.name}");
  105. // Also add it to our walls list
  106. if (!walls.Contains(obj))
  107. {
  108. walls.Add(obj);
  109. Debug.Log($"Added newly tagged wall to tracking: {obj.name}");
  110. }
  111. }
  112. }
  113. }
  114. if (fixedWalls > 0)
  115. {
  116. Debug.Log($"Fixed {fixedWalls} existing walls that weren't properly tagged");
  117. }
  118. else
  119. {
  120. Debug.Log("No walls found at all. This might indicate InitialRoomSetup hasn't run or there's a scene setup issue.");
  121. // Debug: List some objects to see what's in the scene
  122. Debug.Log("Sample objects in scene:");
  123. for (int i = 0; i < Mathf.Min(20, allObjects.Length); i++)
  124. {
  125. if (allObjects[i].name.Contains("Wall") || allObjects[i].name.Contains("wall") ||
  126. allObjects[i].transform.localScale.y > 2f)
  127. {
  128. Debug.Log($" Potential wall: {allObjects[i].name} - Scale: {allObjects[i].transform.localScale} - Tag: {allObjects[i].tag}");
  129. }
  130. }
  131. }
  132. }
  133. private void EnsurePrefabsExist()
  134. {
  135. // Create basic prefabs if they don't exist
  136. if (wallPrefab == null)
  137. {
  138. wallPrefab = CreateWallPrefab();
  139. Debug.Log("Created wall prefab dynamically");
  140. }
  141. if (wallPointPrefab == null)
  142. {
  143. wallPointPrefab = CreateWallPointPrefab();
  144. Debug.Log("Created wall point prefab dynamically");
  145. }
  146. if (doorOpeningPrefab == null)
  147. {
  148. doorOpeningPrefab = CreateDoorOpeningPrefab();
  149. Debug.Log("Created door opening prefab dynamically");
  150. }
  151. }
  152. #region Prefab Creation
  153. private GameObject CreateWallPrefab()
  154. {
  155. // Create a parent GameObject for the wall
  156. GameObject wall = new GameObject("Wall_Prefab");
  157. // Add a cube as child for the visual representation
  158. GameObject wallMesh = GameObject.CreatePrimitive(PrimitiveType.Cube);
  159. wallMesh.name = "WallMesh";
  160. wallMesh.transform.SetParent(wall.transform);
  161. wallMesh.transform.localPosition = Vector3.zero;
  162. wallMesh.transform.localRotation = Quaternion.identity;
  163. wallMesh.transform.localScale = Vector3.one;
  164. // Set up the wall material
  165. Renderer renderer = wallMesh.GetComponent<Renderer>();
  166. Material wallMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  167. // Set up proper wall color - light gray/beige
  168. wallMaterial.color = new Color(0.9f, 0.9f, 0.8f); // Light beige/cream color
  169. // Make sure it's not metallic and has proper smoothness
  170. wallMaterial.SetFloat("_Metallic", 0.0f);
  171. wallMaterial.SetFloat("_Smoothness", 0.2f);
  172. renderer.material = wallMaterial;
  173. // Ensure the wall has a collider for door placement detection
  174. BoxCollider collider = wallMesh.GetComponent<BoxCollider>();
  175. if (collider == null)
  176. {
  177. collider = wallMesh.AddComponent<BoxCollider>();
  178. }
  179. wall.tag = "Wall";
  180. // Don't destroy this object, keep it for instantiation
  181. DontDestroyOnLoad(wall);
  182. wall.SetActive(false); // Hide the template
  183. return wall;
  184. }
  185. private GameObject CreateWallPointPrefab()
  186. {
  187. // Create a parent GameObject for the wall point
  188. GameObject point = new GameObject("WallPoint_Prefab");
  189. // Add a sphere as child for the visual representation
  190. GameObject pointMesh = GameObject.CreatePrimitive(PrimitiveType.Sphere);
  191. pointMesh.name = "PointMesh";
  192. pointMesh.transform.SetParent(point.transform);
  193. pointMesh.transform.localPosition = Vector3.zero;
  194. pointMesh.transform.localRotation = Quaternion.identity;
  195. pointMesh.transform.localScale = Vector3.one * 0.2f;
  196. Renderer renderer = pointMesh.GetComponent<Renderer>();
  197. Material pointMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  198. // Set up bright red color for wall points
  199. pointMaterial.color = Color.red;
  200. pointMaterial.SetFloat("_Metallic", 0.0f);
  201. pointMaterial.SetFloat("_Smoothness", 0.8f); // Make it a bit shinier for visibility
  202. renderer.material = pointMaterial;
  203. // Remove collider to prevent interference
  204. Collider collider = pointMesh.GetComponent<Collider>();
  205. if (collider != null) DestroyImmediate(collider);
  206. DontDestroyOnLoad(point);
  207. point.SetActive(false); // Hide the template
  208. return point;
  209. }
  210. private GameObject CreateDoorOpeningPrefab()
  211. {
  212. // Create a parent GameObject for the door frame (visible part)
  213. GameObject door = new GameObject("DoorOpening_Prefab");
  214. // Create door frame - just the frame, not a solid door
  215. GameObject doorFrame = new GameObject("DoorFrame");
  216. doorFrame.transform.SetParent(door.transform);
  217. // Create frame components: left post, right post, top beam
  218. // Posts should be positioned at ground level with proper Y positioning
  219. CreateDoorFramePost(doorFrame, "LeftPost", new Vector3(-doorWidth / 2f, doorHeight / 2f, 0f));
  220. CreateDoorFramePost(doorFrame, "RightPost", new Vector3(doorWidth / 2f, doorHeight / 2f, 0f));
  221. CreateDoorFrameBeam(doorFrame, "TopBeam", new Vector3(0f, doorHeight - 0.1f, 0f));
  222. door.tag = "Door";
  223. DontDestroyOnLoad(door);
  224. return door;
  225. }
  226. private void CreateDoorFramePost(GameObject parent, string name, Vector3 position)
  227. {
  228. GameObject post = GameObject.CreatePrimitive(PrimitiveType.Cube);
  229. post.name = name;
  230. post.transform.SetParent(parent.transform);
  231. post.transform.localPosition = position;
  232. post.transform.localScale = new Vector3(0.1f, doorHeight, 0.2f); // Thin post
  233. Renderer renderer = post.GetComponent<Renderer>();
  234. Material frameMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  235. frameMaterial.color = new Color(0.4f, 0.2f, 0.1f); // Brown wood
  236. frameMaterial.SetFloat("_Metallic", 0.0f);
  237. frameMaterial.SetFloat("_Smoothness", 0.3f);
  238. renderer.material = frameMaterial;
  239. }
  240. private void CreateDoorFrameBeam(GameObject parent, string name, Vector3 position)
  241. {
  242. GameObject beam = GameObject.CreatePrimitive(PrimitiveType.Cube);
  243. beam.name = name;
  244. beam.transform.SetParent(parent.transform);
  245. beam.transform.localPosition = position;
  246. beam.transform.localScale = new Vector3(doorWidth + 0.2f, 0.2f, 0.2f); // Wide beam across top
  247. Renderer renderer = beam.GetComponent<Renderer>();
  248. Material frameMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  249. frameMaterial.color = new Color(0.4f, 0.2f, 0.1f); // Brown wood
  250. frameMaterial.SetFloat("_Metallic", 0.0f);
  251. frameMaterial.SetFloat("_Smoothness", 0.3f);
  252. renderer.material = frameMaterial;
  253. }
  254. #endregion
  255. #region Main Update Loop
  256. private void Update()
  257. {
  258. switch (currentMode)
  259. {
  260. case BuildingUIController.BuildingMode.CreatingWalls:
  261. HandleWallCreation();
  262. break;
  263. case BuildingUIController.BuildingMode.CreatingDoors:
  264. HandleDoorPlacement();
  265. break;
  266. case BuildingUIController.BuildingMode.CreatingEntrance:
  267. HandleEntranceCreation();
  268. break;
  269. default:
  270. HandleNormalMode();
  271. HideAllPreviews();
  272. break;
  273. }
  274. }
  275. public void SetBuildingMode(BuildingUIController.BuildingMode mode)
  276. {
  277. // Cancel any current wall creation
  278. if (isCreatingWall)
  279. {
  280. CancelWallCreation();
  281. }
  282. currentMode = mode;
  283. HideAllPreviews();
  284. Debug.Log($"Building mode changed to: {mode}");
  285. }
  286. #endregion
  287. #region Normal Mode
  288. private void HandleNormalMode()
  289. {
  290. // In normal mode, allow deletion of entrances with right-click
  291. if (Input.GetMouseButtonDown(1)) // Right click
  292. {
  293. Vector3 mousePos = GetMouseWorldPosition();
  294. CheckForEntranceDeletion(mousePos);
  295. }
  296. }
  297. private void CheckForEntranceDeletion(Vector3 mousePos)
  298. {
  299. Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);
  300. if (Physics.Raycast(ray, out RaycastHit hit, 1000f))
  301. {
  302. GameObject hitObj = hit.collider.gameObject;
  303. // Check if we hit an entrance or entrance component
  304. GameObject entranceToDelete = null;
  305. if (hitObj.CompareTag("Entrance"))
  306. {
  307. entranceToDelete = hitObj;
  308. }
  309. else if (hitObj.transform.parent != null && hitObj.transform.parent.CompareTag("Entrance"))
  310. {
  311. entranceToDelete = hitObj.transform.parent.gameObject;
  312. }
  313. if (entranceToDelete != null)
  314. {
  315. Debug.Log($"Deleting entrance: {entranceToDelete.name}");
  316. DestroyImmediate(entranceToDelete);
  317. // Note: The wall segments around the entrance will remain
  318. // This creates a permanent opening where the entrance was
  319. }
  320. }
  321. }
  322. #endregion
  323. #region Wall Creation
  324. private void HandleWallCreation()
  325. {
  326. Vector3 mousePos = GetMouseWorldPosition();
  327. if (Input.GetMouseButtonDown(0)) // Left click
  328. {
  329. if (!isCreatingWall)
  330. {
  331. // Start creating a wall
  332. StartWallCreation(mousePos);
  333. }
  334. else
  335. {
  336. // Finish creating the wall
  337. FinishWallCreation(mousePos);
  338. }
  339. }
  340. else if (Input.GetMouseButtonDown(1)) // Right click
  341. {
  342. // Cancel wall creation
  343. if (isCreatingWall)
  344. {
  345. CancelWallCreation();
  346. }
  347. }
  348. // Update preview while creating wall
  349. if (isCreatingWall)
  350. {
  351. UpdateWallPreview(mousePos);
  352. }
  353. }
  354. private void StartWallCreation(Vector3 startPoint)
  355. {
  356. // Snap to nearby existing points
  357. Vector3 snappedStart = SnapToNearbyPoint(startPoint);
  358. wallStartPoint = snappedStart;
  359. isCreatingWall = true;
  360. // Show preview
  361. if (previewLine != null)
  362. {
  363. previewLine.enabled = true;
  364. }
  365. Debug.Log($"Started wall creation at: {wallStartPoint}");
  366. }
  367. private void UpdateWallPreview(Vector3 currentMousePos)
  368. {
  369. if (!isCreatingWall || previewLine == null) return;
  370. // Calculate snapped end point
  371. Vector3 snappedEndPoint = SnapToAngle(wallStartPoint, currentMousePos);
  372. Vector3 finalSnappedPoint = SnapToNearbyPoint(snappedEndPoint);
  373. // Show snap indicator if we're snapping to something
  374. if (Vector3.Distance(finalSnappedPoint, snappedEndPoint) > 0.1f)
  375. {
  376. ShowSnapIndicator(finalSnappedPoint);
  377. }
  378. else
  379. {
  380. HideSnapIndicator();
  381. }
  382. // Update preview line
  383. previewLine.SetPosition(0, wallStartPoint);
  384. previewLine.SetPosition(1, finalSnappedPoint);
  385. }
  386. private void ShowSnapIndicator(Vector3 position)
  387. {
  388. if (snapIndicator != null)
  389. {
  390. snapIndicator.transform.position = position;
  391. snapIndicator.SetActive(true);
  392. }
  393. }
  394. private void HideSnapIndicator()
  395. {
  396. if (snapIndicator != null)
  397. {
  398. snapIndicator.SetActive(false);
  399. }
  400. }
  401. private void FinishWallCreation(Vector3 endPoint)
  402. {
  403. if (!isCreatingWall) return;
  404. // Calculate snapped end point
  405. Vector3 snappedEndPoint = SnapToAngle(wallStartPoint, endPoint);
  406. snappedEndPoint = SnapToNearbyPoint(snappedEndPoint);
  407. // Create the actual wall
  408. CreateWall(wallStartPoint, snappedEndPoint);
  409. // Reset state
  410. isCreatingWall = false;
  411. if (previewLine != null)
  412. {
  413. previewLine.enabled = false;
  414. }
  415. Debug.Log($"Created wall from {wallStartPoint} to {snappedEndPoint}");
  416. }
  417. private void CancelWallCreation()
  418. {
  419. isCreatingWall = false;
  420. if (previewLine != null)
  421. {
  422. previewLine.enabled = false;
  423. }
  424. Debug.Log("Wall creation cancelled");
  425. }
  426. private Vector3 SnapToAngle(Vector3 startPoint, Vector3 endPoint)
  427. {
  428. Vector3 direction = (endPoint - startPoint).normalized;
  429. float distance = Vector3.Distance(startPoint, endPoint);
  430. // Calculate angle in degrees
  431. float currentAngle = Mathf.Atan2(direction.z, direction.x) * Mathf.Rad2Deg;
  432. if (currentAngle < 0) currentAngle += 360f;
  433. // Find closest snap angle
  434. float closestAngle = snapAngles[0];
  435. float smallestDifference = Mathf.Abs(currentAngle - closestAngle);
  436. foreach (float angle in snapAngles)
  437. {
  438. float difference = Mathf.Abs(currentAngle - angle);
  439. if (difference > 180f) difference = 360f - difference; // Handle wrapping
  440. if (difference < smallestDifference)
  441. {
  442. smallestDifference = difference;
  443. closestAngle = angle;
  444. }
  445. }
  446. // Calculate snapped direction
  447. float rad = closestAngle * Mathf.Deg2Rad;
  448. Vector3 snappedDirection = new Vector3(Mathf.Cos(rad), 0f, Mathf.Sin(rad));
  449. return startPoint + snappedDirection * distance;
  450. }
  451. private Vector3 SnapToNearbyPoint(Vector3 point)
  452. {
  453. float closestCornerDistance = float.MaxValue;
  454. float closestWallDistance = float.MaxValue;
  455. Vector3 closestCornerPoint = point;
  456. Vector3 closestWallPoint = point;
  457. bool foundCorner = false;
  458. foreach (GameObject wall in walls)
  459. {
  460. if (wall == null) continue;
  461. // First priority: Check both endpoints of the wall (corners)
  462. Vector3[] endpoints = GetWallEndpoints(wall);
  463. foreach (Vector3 endpoint in endpoints)
  464. {
  465. float distance = Vector3.Distance(point, endpoint);
  466. if (distance < snapDistance && distance < closestCornerDistance)
  467. {
  468. closestCornerDistance = distance;
  469. closestCornerPoint = endpoint;
  470. foundCorner = true;
  471. Debug.Log($"Found corner snap point at {endpoint}, distance: {distance}");
  472. }
  473. }
  474. // Second priority: Check snapping to wall surface/center (only if no corner found nearby)
  475. if (!foundCorner || closestCornerDistance > snapDistance * 0.7f) // Allow wall snapping if no close corner
  476. {
  477. Vector3 wallCenter = wall.transform.position;
  478. wallCenter.y = 0f; // Project to ground level
  479. // Project point onto wall line to find closest point on wall
  480. Vector3 wallDirection = wall.transform.forward;
  481. Vector3 toPoint = point - wallCenter;
  482. float projection = Vector3.Dot(toPoint, wallDirection);
  483. // Clamp projection to wall bounds
  484. float wallLength = wall.transform.localScale.z;
  485. projection = Mathf.Clamp(projection, -wallLength / 2f, wallLength / 2f);
  486. Vector3 closestPointOnWall = wallCenter + wallDirection * projection;
  487. float wallDistance = Vector3.Distance(point, closestPointOnWall);
  488. // Snap to wall surface if clicking near the wall
  489. if (wallDistance < snapDistance && wallDistance < closestWallDistance)
  490. {
  491. closestWallDistance = wallDistance;
  492. closestWallPoint = closestPointOnWall;
  493. Debug.Log($"Found wall surface snap point at {closestPointOnWall}, distance: {wallDistance}");
  494. }
  495. }
  496. }
  497. // Return the best snap point: prioritize corners over wall surfaces
  498. if (foundCorner && closestCornerDistance < snapDistance)
  499. {
  500. Debug.Log($"Using corner snap point: {closestCornerPoint}");
  501. UpdateSnapIndicatorColor(true); // Corner = cyan
  502. return closestCornerPoint;
  503. }
  504. else if (closestWallDistance < snapDistance)
  505. {
  506. Debug.Log($"Using wall surface snap point: {closestWallPoint}");
  507. UpdateSnapIndicatorColor(false); // Wall surface = yellow
  508. return closestWallPoint;
  509. }
  510. Debug.Log($"No snap point found, using original point: {point}");
  511. return point;
  512. }
  513. private void UpdateSnapIndicatorColor(bool isCorner)
  514. {
  515. if (snapIndicator != null)
  516. {
  517. Renderer renderer = snapIndicator.GetComponent<Renderer>();
  518. if (renderer != null)
  519. {
  520. Color indicatorColor = isCorner ? Color.cyan : Color.yellow;
  521. Color emissionColor = indicatorColor * 2f;
  522. renderer.material.color = indicatorColor;
  523. renderer.material.SetColor("_EmissionColor", emissionColor);
  524. }
  525. }
  526. }
  527. private void CreateWall(Vector3 startPoint, Vector3 endPoint)
  528. {
  529. if (Vector3.Distance(startPoint, endPoint) < 0.1f) return; // Too short
  530. // Calculate wall properties
  531. Vector3 center = (startPoint + endPoint) / 2f;
  532. center.y = wallHeight / 2f; // Set proper height
  533. Vector3 direction = (endPoint - startPoint).normalized;
  534. float length = Vector3.Distance(startPoint, endPoint);
  535. // Create wall object from prefab
  536. GameObject wall = Instantiate(wallPrefab, center, Quaternion.LookRotation(direction, Vector3.up));
  537. wall.SetActive(true); // Make sure it's visible
  538. // Scale the entire wall object to proper dimensions:
  539. // X = thickness (perpendicular to wall direction)
  540. // Y = height (up/down)
  541. // Z = length (along the wall direction)
  542. wall.transform.localScale = new Vector3(wallThickness, wallHeight, length);
  543. // Set wall name and add to list
  544. wall.name = $"Wall_{walls.Count}";
  545. walls.Add(wall);
  546. Debug.Log($"Created wall: {wall.name} from {startPoint} to {endPoint}, length: {length}");
  547. }
  548. #endregion
  549. #region Door Placement
  550. private void HandleDoorPlacement()
  551. {
  552. Vector3 mousePos = GetMouseWorldPosition();
  553. // Find wall under mouse
  554. GameObject wallUnderMouse = FindWallUnderMouse(mousePos);
  555. // Update hover preview
  556. UpdateDoorPreview(wallUnderMouse, mousePos);
  557. if (Input.GetMouseButtonDown(0)) // Left click
  558. {
  559. Debug.Log($"Door placement click detected at {mousePos}");
  560. if (wallUnderMouse != null)
  561. {
  562. Debug.Log($"Wall found under mouse: {wallUnderMouse.name}");
  563. PlaceDoorOnWall(wallUnderMouse, mousePos);
  564. }
  565. else
  566. {
  567. Debug.LogWarning("No wall found under mouse cursor for door placement");
  568. // Let's try a different approach - check nearby walls
  569. GameObject nearestWall = FindNearestWall(mousePos);
  570. if (nearestWall != null)
  571. {
  572. Debug.Log($"Found nearest wall: {nearestWall.name}, placing door there");
  573. PlaceDoorOnWall(nearestWall, mousePos);
  574. }
  575. else
  576. {
  577. Debug.LogWarning("No walls found nearby for door placement");
  578. }
  579. }
  580. }
  581. }
  582. private void UpdateDoorPreview(GameObject wall, Vector3 mousePos)
  583. {
  584. if (wall != hoveredWall)
  585. {
  586. hoveredWall = wall;
  587. if (wall != null)
  588. {
  589. ShowDoorPreview(wall, mousePos);
  590. }
  591. else
  592. {
  593. HideDoorPreview();
  594. }
  595. }
  596. else if (wall != null)
  597. {
  598. // Update preview position
  599. ShowDoorPreview(wall, mousePos);
  600. }
  601. }
  602. private void ShowDoorPreview(GameObject wall, Vector3 mousePos)
  603. {
  604. if (doorPreview == null) return;
  605. // Calculate door position on the wall
  606. Vector3 doorPosition = CalculateDoorPositionOnWall(wall, mousePos);
  607. // Position and orient the preview - door should face perpendicular to wall
  608. doorPreview.transform.position = doorPosition;
  609. doorPreview.transform.rotation = Quaternion.LookRotation(wall.transform.right);
  610. doorPreview.SetActive(true);
  611. }
  612. private void HideDoorPreview()
  613. {
  614. if (doorPreview != null)
  615. {
  616. doorPreview.SetActive(false);
  617. }
  618. }
  619. private void PlaceDoorOnWall(GameObject wall, Vector3 mousePos)
  620. {
  621. Debug.Log($"Attempting to place door on {wall.name} at mouse position {mousePos}");
  622. // Calculate door position
  623. Vector3 doorPosition = CalculateDoorPositionOnWall(wall, mousePos);
  624. Debug.Log($"Calculated door position: {doorPosition}");
  625. // Check if door would intersect with existing doors
  626. if (WouldDoorIntersectExistingDoors(wall, doorPosition))
  627. {
  628. Debug.LogWarning("Cannot place door - would intersect with existing door");
  629. return;
  630. }
  631. // Get wall endpoints and direction for splitting
  632. Vector3[] wallEndpoints = GetWallEndpoints(wall);
  633. Vector3 wallStart = wallEndpoints[0];
  634. Vector3 wallEnd = wallEndpoints[1];
  635. Vector3 wallDirection = wall.transform.forward;
  636. // Calculate door boundaries along the wall
  637. Vector3 doorStart = doorPosition - wallDirection * (doorWidth / 2f);
  638. Vector3 doorEnd = doorPosition + wallDirection * (doorWidth / 2f);
  639. // Create door at wall position with proper rotation
  640. // Door should face perpendicular to the wall direction (reuse existing wallDirection)
  641. Quaternion doorRotation = Quaternion.LookRotation(wall.transform.right); // Face perpendicular to wall
  642. GameObject door = Instantiate(doorOpeningPrefab, doorPosition, doorRotation);
  643. door.SetActive(true);
  644. door.name = $"Door_on_{wall.name}";
  645. // Split the original wall into two segments around the door
  646. SplitWallAroundDoor(wall, wallStart, wallEnd, doorStart, doorEnd);
  647. Debug.Log($"Successfully placed door: {door.name} and split wall into segments");
  648. }
  649. private bool WouldDoorIntersectExistingDoors(GameObject wall, Vector3 doorPosition)
  650. {
  651. // Find all existing doors
  652. GameObject[] existingDoors = GameObject.FindGameObjectsWithTag("Door");
  653. foreach (GameObject existingDoor in existingDoors)
  654. {
  655. // Check if doors are on the same wall or parallel walls
  656. float distance = Vector3.Distance(doorPosition, existingDoor.transform.position);
  657. if (distance < doorWidth * 1.5f) // Doors too close
  658. {
  659. Debug.Log($"Door too close to existing door {existingDoor.name}: distance = {distance}");
  660. return true;
  661. }
  662. }
  663. return false;
  664. }
  665. private void SplitWallAroundDoor(GameObject originalWall, Vector3 wallStart, Vector3 wallEnd, Vector3 doorStart, Vector3 doorEnd)
  666. {
  667. // Calculate the two new wall segments
  668. float originalWallLength = Vector3.Distance(wallStart, wallEnd);
  669. float leftSegmentLength = Vector3.Distance(wallStart, doorStart);
  670. float rightSegmentLength = Vector3.Distance(doorEnd, wallEnd);
  671. // Only create segments if they're long enough
  672. bool createLeftSegment = leftSegmentLength > 0.1f;
  673. bool createRightSegment = rightSegmentLength > 0.1f;
  674. Debug.Log($"Splitting wall: original length = {originalWallLength}, left = {leftSegmentLength}, right = {rightSegmentLength}");
  675. if (createLeftSegment)
  676. {
  677. // Create left wall segment - full height
  678. Vector3 leftCenter = (wallStart + doorStart) / 2f;
  679. leftCenter.y = wallHeight / 2f;
  680. GameObject leftWall = Instantiate(wallPrefab, leftCenter, originalWall.transform.rotation);
  681. leftWall.SetActive(true);
  682. leftWall.name = $"{originalWall.name}_Left";
  683. leftWall.transform.localScale = new Vector3(wallThickness, wallHeight, leftSegmentLength);
  684. walls.Add(leftWall);
  685. Debug.Log($"Created left wall segment: {leftWall.name}");
  686. }
  687. if (createRightSegment)
  688. {
  689. // Create right wall segment - full height
  690. Vector3 rightCenter = (doorEnd + wallEnd) / 2f;
  691. rightCenter.y = wallHeight / 2f;
  692. GameObject rightWall = Instantiate(wallPrefab, rightCenter, originalWall.transform.rotation);
  693. rightWall.SetActive(true);
  694. rightWall.name = $"{originalWall.name}_Right";
  695. rightWall.transform.localScale = new Vector3(wallThickness, wallHeight, rightSegmentLength);
  696. walls.Add(rightWall);
  697. Debug.Log($"Created right wall segment: {rightWall.name}");
  698. }
  699. // Create header beam above the door (if there are segments on both sides)
  700. if (createLeftSegment && createRightSegment)
  701. {
  702. CreateDoorHeaderBeam(originalWall, doorStart, doorEnd);
  703. }
  704. // Remove original wall from list and destroy it
  705. walls.Remove(originalWall);
  706. DestroyImmediate(originalWall);
  707. Debug.Log("Removed original wall after splitting");
  708. }
  709. private void CreateDoorHeaderBeam(GameObject originalWall, Vector3 doorStart, Vector3 doorEnd)
  710. {
  711. // Create beam above door opening
  712. Vector3 beamCenter = (doorStart + doorEnd) / 2f;
  713. beamCenter.y = doorHeight + 0.1f; // Just above the door
  714. GameObject headerBeam = Instantiate(wallPrefab, beamCenter, originalWall.transform.rotation);
  715. headerBeam.SetActive(true);
  716. headerBeam.name = $"{originalWall.name}_Header";
  717. float beamLength = Vector3.Distance(doorStart, doorEnd);
  718. float beamHeight = wallHeight - doorHeight - 0.1f; // Remaining height above door
  719. if (beamHeight > 0.1f) // Only create beam if there's significant height remaining
  720. {
  721. headerBeam.transform.localScale = new Vector3(wallThickness, beamHeight, beamLength);
  722. walls.Add(headerBeam);
  723. Debug.Log($"Created door header beam: {headerBeam.name}");
  724. }
  725. else
  726. {
  727. // If no room for header beam, destroy it
  728. DestroyImmediate(headerBeam);
  729. Debug.Log("Door is full height - no header beam needed");
  730. }
  731. }
  732. #endregion
  733. #region Entrance Creation
  734. private void HandleEntranceCreation()
  735. {
  736. Vector3 mousePos = GetMouseWorldPosition();
  737. // Find wall under mouse
  738. GameObject wallUnderMouse = FindWallUnderMouse(mousePos);
  739. // Update entrance preview (similar to door but different style)
  740. UpdateEntrancePreview(wallUnderMouse, mousePos);
  741. if (Input.GetMouseButtonDown(0)) // Left click
  742. {
  743. Debug.Log($"Entrance placement click detected at {mousePos}");
  744. if (wallUnderMouse != null)
  745. {
  746. Debug.Log($"Wall found under mouse: {wallUnderMouse.name}");
  747. PlaceEntranceOnWall(wallUnderMouse, mousePos);
  748. }
  749. else
  750. {
  751. Debug.LogWarning("No wall found under mouse cursor for entrance placement");
  752. // Try alternative detection method first
  753. GameObject alternativeWall = FindWallUnderMouseAlternative(mousePos);
  754. if (alternativeWall != null)
  755. {
  756. Debug.Log($"Alternative method found wall: {alternativeWall.name}, placing entrance there");
  757. PlaceEntranceOnWall(alternativeWall, mousePos);
  758. }
  759. else
  760. {
  761. // Let's try a different approach - check nearby walls
  762. GameObject nearestWall = FindNearestWall(mousePos);
  763. if (nearestWall != null)
  764. {
  765. Debug.Log($"Found nearest wall: {nearestWall.name}, placing entrance there");
  766. PlaceEntranceOnWall(nearestWall, mousePos);
  767. }
  768. else
  769. {
  770. Debug.LogWarning("No walls found nearby for entrance placement");
  771. }
  772. }
  773. }
  774. }
  775. }
  776. private void UpdateEntrancePreview(GameObject wall, Vector3 mousePos)
  777. {
  778. if (wall != null)
  779. {
  780. ShowEntrancePreview(wall, mousePos);
  781. }
  782. else
  783. {
  784. HideEntrancePreview();
  785. }
  786. }
  787. private void ShowEntrancePreview(GameObject wall, Vector3 mousePos)
  788. {
  789. if (doorPreview == null) return; // Reuse door preview for now
  790. // Calculate entrance position on the wall
  791. Vector3 entrancePosition = CalculateDoorPositionOnWall(wall, mousePos);
  792. // Position and orient the preview - entrance should face perpendicular to wall
  793. doorPreview.transform.position = entrancePosition;
  794. doorPreview.transform.rotation = Quaternion.LookRotation(wall.transform.right);
  795. // Make entrance preview slightly different (maybe different scale or color)
  796. doorPreview.transform.localScale = new Vector3(0.2f, doorHeight, doorWidth * 1.2f); // Slightly wider
  797. doorPreview.SetActive(true);
  798. }
  799. private void HideEntrancePreview()
  800. {
  801. if (doorPreview != null)
  802. {
  803. doorPreview.SetActive(false);
  804. }
  805. }
  806. private void PlaceEntranceOnWall(GameObject wall, Vector3 mousePos)
  807. {
  808. Debug.Log($"Attempting to place entrance on {wall.name} at mouse position {mousePos}");
  809. // Calculate entrance position on the wall surface
  810. Vector3 entrancePosition = CalculateDoorPositionOnWall(wall, mousePos);
  811. Debug.Log($"Calculated entrance position: {entrancePosition}");
  812. // Check if there's already an entrance
  813. GameObject[] existingEntrances = GameObject.FindGameObjectsWithTag("Entrance");
  814. if (existingEntrances.Length > 0)
  815. {
  816. Debug.LogWarning("Building already has an entrance. Replacing existing entrance.");
  817. foreach (GameObject existingEntrance in existingEntrances)
  818. {
  819. DestroyImmediate(existingEntrance);
  820. }
  821. }
  822. // Determine wall orientation based on its scale
  823. Vector3 wallScale = wall.transform.localScale;
  824. bool isNorthSouthWall = wallScale.x > wallScale.z; // Wide in X means North/South wall
  825. Debug.Log($"Wall scale: {wallScale}, isNorthSouthWall: {isNorthSouthWall}");
  826. // Calculate entrance boundaries and determine how to split the wall
  827. float entranceWidth = doorWidth * 1.5f;
  828. // Create entrance with proper rotation
  829. GameObject entrance = CreateEntrancePrefab();
  830. entrance.transform.position = entrancePosition;
  831. // Set rotation based on wall orientation
  832. if (isNorthSouthWall)
  833. {
  834. // For North/South walls (extending in X), entrance should face along Z-axis
  835. entrance.transform.rotation = Quaternion.identity; // Facing forward (positive Z)
  836. }
  837. else
  838. {
  839. // For East/West walls (extending in Z), entrance should face along X-axis
  840. entrance.transform.rotation = Quaternion.Euler(0, 90, 0); // Facing right (positive X)
  841. }
  842. entrance.SetActive(true);
  843. entrance.name = "BuildingEntrance";
  844. entrance.tag = "Entrance";
  845. Debug.Log($"Placed entrance at {entrance.transform.position} with rotation {entrance.transform.rotation.eulerAngles}");
  846. // Split the wall properly based on its orientation
  847. SplitWallForEntrance(wall, entrancePosition, entranceWidth, isNorthSouthWall);
  848. Debug.Log($"Successfully placed entrance and split wall");
  849. }
  850. private void SplitWallForEntrance(GameObject originalWall, Vector3 entrancePosition, float entranceWidth, bool isNorthSouthWall)
  851. {
  852. Vector3 wallPos = originalWall.transform.position;
  853. Vector3 wallScale = originalWall.transform.localScale;
  854. Quaternion wallRotation = originalWall.transform.rotation;
  855. // Get the original wall's material to maintain consistency
  856. Material originalMaterial = originalWall.GetComponent<Renderer>()?.material;
  857. Debug.Log($"Splitting wall: {originalWall.name} at position {wallPos} with scale {wallScale}");
  858. if (isNorthSouthWall)
  859. {
  860. // Wall extends in X direction, split along X-axis
  861. float wallLength = wallScale.x; // Corrected: X is the length for North/South walls
  862. float wallLeft = wallPos.x - wallLength / 2f;
  863. float wallRight = wallPos.x + wallLength / 2f;
  864. float entranceLeft = entrancePosition.x - entranceWidth / 2f;
  865. float entranceRight = entrancePosition.x + entranceWidth / 2f;
  866. Debug.Log($"North/South wall split: wallLeft={wallLeft}, wallRight={wallRight}, entranceLeft={entranceLeft}, entranceRight={entranceRight}");
  867. // Create left segment if there's enough space
  868. if (entranceLeft - wallLeft > 0.5f)
  869. {
  870. float leftLength = entranceLeft - wallLeft;
  871. Vector3 leftCenter = new Vector3(wallLeft + leftLength / 2f, wallPos.y, wallPos.z);
  872. GameObject leftWall = Instantiate(wallPrefab, leftCenter, wallRotation);
  873. leftWall.SetActive(true);
  874. leftWall.name = $"{originalWall.name}_Left_Entrance";
  875. leftWall.transform.localScale = new Vector3(leftLength, wallScale.y, wallScale.z);
  876. leftWall.tag = "Wall";
  877. // Apply original material if available
  878. if (originalMaterial != null)
  879. {
  880. leftWall.GetComponent<Renderer>().material = originalMaterial;
  881. }
  882. walls.Add(leftWall);
  883. Debug.Log($"Created left wall segment: scale {leftWall.transform.localScale} at {leftWall.transform.position}");
  884. }
  885. // Create right segment if there's enough space
  886. if (wallRight - entranceRight > 0.5f)
  887. {
  888. float rightLength = wallRight - entranceRight;
  889. Vector3 rightCenter = new Vector3(entranceRight + rightLength / 2f, wallPos.y, wallPos.z);
  890. GameObject rightWall = Instantiate(wallPrefab, rightCenter, wallRotation);
  891. rightWall.SetActive(true);
  892. rightWall.name = $"{originalWall.name}_Right_Entrance";
  893. rightWall.transform.localScale = new Vector3(rightLength, wallScale.y, wallScale.z);
  894. rightWall.tag = "Wall";
  895. // Apply original material if available
  896. if (originalMaterial != null)
  897. {
  898. rightWall.GetComponent<Renderer>().material = originalMaterial;
  899. }
  900. walls.Add(rightWall);
  901. Debug.Log($"Created right wall segment: scale {rightWall.transform.localScale} at {rightWall.transform.position}");
  902. }
  903. }
  904. else
  905. {
  906. // Wall extends in Z direction, split along Z-axis
  907. float wallLength = wallScale.z;
  908. float wallFront = wallPos.z - wallLength / 2f;
  909. float wallBack = wallPos.z + wallLength / 2f;
  910. float entranceFront = entrancePosition.z - entranceWidth / 2f;
  911. float entranceBack = entrancePosition.z + entranceWidth / 2f;
  912. Debug.Log($"East/West wall split: wallFront={wallFront}, wallBack={wallBack}, entranceFront={entranceFront}, entranceBack={entranceBack}");
  913. // Create front segment if there's enough space
  914. if (entranceFront - wallFront > 0.5f)
  915. {
  916. float frontLength = entranceFront - wallFront;
  917. Vector3 frontCenter = new Vector3(wallPos.x, wallPos.y, wallFront + frontLength / 2f);
  918. GameObject frontWall = Instantiate(wallPrefab, frontCenter, wallRotation);
  919. frontWall.SetActive(true);
  920. frontWall.name = $"{originalWall.name}_Front_Entrance";
  921. frontWall.transform.localScale = new Vector3(wallScale.x, wallScale.y, frontLength);
  922. frontWall.tag = "Wall";
  923. // Apply original material if available
  924. if (originalMaterial != null)
  925. {
  926. frontWall.GetComponent<Renderer>().material = originalMaterial;
  927. }
  928. walls.Add(frontWall);
  929. Debug.Log($"Created front wall segment: scale {frontWall.transform.localScale} at {frontWall.transform.position}");
  930. }
  931. // Create back segment if there's enough space
  932. if (wallBack - entranceBack > 0.5f)
  933. {
  934. float backLength = wallBack - entranceBack;
  935. Vector3 backCenter = new Vector3(wallPos.x, wallPos.y, entranceBack + backLength / 2f);
  936. GameObject backWall = Instantiate(wallPrefab, backCenter, wallRotation);
  937. backWall.SetActive(true);
  938. backWall.name = $"{originalWall.name}_Back_Entrance";
  939. backWall.transform.localScale = new Vector3(wallScale.x, wallScale.y, backLength);
  940. backWall.tag = "Wall";
  941. // Apply original material if available
  942. if (originalMaterial != null)
  943. {
  944. backWall.GetComponent<Renderer>().material = originalMaterial;
  945. }
  946. walls.Add(backWall);
  947. Debug.Log($"Created back wall segment: scale {backWall.transform.localScale} at {backWall.transform.position}");
  948. }
  949. }
  950. // Remove original wall
  951. walls.Remove(originalWall);
  952. DestroyImmediate(originalWall);
  953. Debug.Log("Removed original wall after splitting for entrance");
  954. }
  955. private GameObject CreateEntrancePrefab()
  956. {
  957. // Create a more elaborate entrance than a regular door
  958. GameObject entrance = new GameObject("BuildingEntrance");
  959. // Create entrance frame - wider and more elaborate
  960. GameObject entranceFrame = new GameObject("EntranceFrame");
  961. entranceFrame.transform.SetParent(entrance.transform);
  962. float entranceWidth = doorWidth * 1.5f;
  963. // Create frame components: left post, right post, top beam, and entrance mat
  964. CreateEntrancePost(entranceFrame, "LeftPost", new Vector3(-entranceWidth / 2f, doorHeight / 2f, 0f), entranceWidth);
  965. CreateEntrancePost(entranceFrame, "RightPost", new Vector3(entranceWidth / 2f, doorHeight / 2f, 0f), entranceWidth);
  966. CreateEntranceBeam(entranceFrame, "TopBeam", new Vector3(0f, doorHeight - 0.1f, 0f), entranceWidth);
  967. CreateEntranceMat(entranceFrame, "WelcomeMat", new Vector3(0f, 0.05f, 1f), entranceWidth);
  968. entrance.tag = "Entrance";
  969. DontDestroyOnLoad(entrance);
  970. return entrance;
  971. }
  972. private void CreateEntrancePost(GameObject parent, string name, Vector3 position, float width)
  973. {
  974. GameObject post = GameObject.CreatePrimitive(PrimitiveType.Cube);
  975. post.name = name;
  976. post.transform.SetParent(parent.transform);
  977. post.transform.localPosition = position;
  978. post.transform.localScale = new Vector3(0.15f, doorHeight, 0.3f); // Slightly thicker than door posts
  979. Renderer renderer = post.GetComponent<Renderer>();
  980. Material frameMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  981. frameMaterial.color = new Color(0.3f, 0.15f, 0.05f); // Darker brown for entrance
  982. frameMaterial.SetFloat("_Metallic", 0.0f);
  983. frameMaterial.SetFloat("_Smoothness", 0.4f);
  984. renderer.material = frameMaterial;
  985. }
  986. private void CreateEntranceBeam(GameObject parent, string name, Vector3 position, float width)
  987. {
  988. GameObject beam = GameObject.CreatePrimitive(PrimitiveType.Cube);
  989. beam.name = name;
  990. beam.transform.SetParent(parent.transform);
  991. beam.transform.localPosition = position;
  992. beam.transform.localScale = new Vector3(width + 0.3f, 0.3f, 0.3f); // Wider and thicker beam
  993. Renderer renderer = beam.GetComponent<Renderer>();
  994. Material frameMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  995. frameMaterial.color = new Color(0.3f, 0.15f, 0.05f); // Darker brown for entrance
  996. frameMaterial.SetFloat("_Metallic", 0.0f);
  997. frameMaterial.SetFloat("_Smoothness", 0.4f);
  998. renderer.material = frameMaterial;
  999. }
  1000. private void CreateEntranceMat(GameObject parent, string name, Vector3 position, float width)
  1001. {
  1002. GameObject mat = GameObject.CreatePrimitive(PrimitiveType.Cube);
  1003. mat.name = name;
  1004. mat.transform.SetParent(parent.transform);
  1005. mat.transform.localPosition = position;
  1006. mat.transform.localScale = new Vector3(width, 0.1f, 1.5f); // Welcome mat dimensions
  1007. Renderer renderer = mat.GetComponent<Renderer>();
  1008. Material matMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  1009. matMaterial.color = new Color(0.8f, 0.2f, 0.2f); // Red welcome mat
  1010. matMaterial.SetFloat("_Metallic", 0.0f);
  1011. matMaterial.SetFloat("_Smoothness", 0.1f); // Rough mat texture
  1012. renderer.material = matMaterial;
  1013. }
  1014. #endregion
  1015. #region Helper Methods
  1016. private void CreatePreviewLine()
  1017. {
  1018. GameObject previewObj = new GameObject("WallPreview");
  1019. previewLine = previewObj.AddComponent<LineRenderer>();
  1020. // Use URP Unlit shader for line renderer (better for simple colored lines)
  1021. previewLine.material = new Material(Shader.Find("Universal Render Pipeline/Unlit"));
  1022. previewLine.material.color = Color.yellow;
  1023. previewLine.startColor = Color.yellow;
  1024. previewLine.endColor = Color.yellow;
  1025. previewLine.startWidth = 0.1f;
  1026. previewLine.endWidth = 0.1f;
  1027. previewLine.positionCount = 2;
  1028. previewLine.enabled = false;
  1029. }
  1030. private void CreateDoorPreview()
  1031. {
  1032. // Create a simple preview object
  1033. doorPreview = GameObject.CreatePrimitive(PrimitiveType.Cube);
  1034. doorPreview.name = "DoorPreview";
  1035. // Make it transparent green
  1036. Renderer renderer = doorPreview.GetComponent<Renderer>();
  1037. Material previewMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  1038. // Set up bright green transparent color
  1039. previewMaterial.color = new Color(0f, 1f, 0f, 0.6f); // Bright transparent green
  1040. // Set up transparency properly for URP
  1041. previewMaterial.SetFloat("_Surface", 1); // Set to Transparent
  1042. previewMaterial.SetFloat("_Blend", 0); // Alpha blend
  1043. previewMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
  1044. previewMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
  1045. previewMaterial.SetInt("_ZWrite", 0);
  1046. previewMaterial.renderQueue = 3000;
  1047. // Make it non-metallic and smooth for better visibility
  1048. previewMaterial.SetFloat("_Metallic", 0.0f);
  1049. previewMaterial.SetFloat("_Smoothness", 0.9f);
  1050. renderer.material = previewMaterial;
  1051. // Scale to door size - match the actual door dimensions
  1052. doorPreview.transform.localScale = new Vector3(0.2f, doorHeight, doorWidth);
  1053. doorPreview.SetActive(false);
  1054. // Remove collider to prevent interference
  1055. Collider collider = doorPreview.GetComponent<Collider>();
  1056. if (collider != null) Destroy(collider);
  1057. }
  1058. private void CreateSnapIndicator()
  1059. {
  1060. snapIndicator = GameObject.CreatePrimitive(PrimitiveType.Sphere);
  1061. snapIndicator.name = "SnapIndicator";
  1062. // Make it a bright, pulsing indicator
  1063. Renderer renderer = snapIndicator.GetComponent<Renderer>();
  1064. Material indicatorMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  1065. indicatorMaterial.color = Color.cyan;
  1066. indicatorMaterial.SetFloat("_Metallic", 0.0f);
  1067. indicatorMaterial.SetFloat("_Smoothness", 0.9f);
  1068. // Make it emissive so it glows
  1069. indicatorMaterial.EnableKeyword("_EMISSION");
  1070. indicatorMaterial.SetColor("_EmissionColor", Color.cyan * 2f);
  1071. renderer.material = indicatorMaterial;
  1072. // Scale it to be visible but not too large
  1073. snapIndicator.transform.localScale = Vector3.one * 0.3f;
  1074. snapIndicator.SetActive(false);
  1075. // Remove collider to prevent interference
  1076. Collider collider = snapIndicator.GetComponent<Collider>();
  1077. if (collider != null) Destroy(collider);
  1078. }
  1079. private void HideAllPreviews()
  1080. {
  1081. if (previewLine != null)
  1082. {
  1083. previewLine.enabled = false;
  1084. }
  1085. HideDoorPreview();
  1086. HideSnapIndicator();
  1087. }
  1088. private Vector3 GetMouseWorldPosition()
  1089. {
  1090. Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);
  1091. // Cast ray onto ground plane (Y = 0)
  1092. if (Physics.Raycast(ray, out RaycastHit hit))
  1093. {
  1094. return hit.point;
  1095. }
  1096. // Fallback: project onto Y = 0 plane
  1097. float distance = -ray.origin.y / ray.direction.y;
  1098. return ray.origin + ray.direction * distance;
  1099. }
  1100. private GameObject FindWallUnderMouse(Vector3 mousePos)
  1101. {
  1102. Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);
  1103. Debug.Log($"Raycasting for wall detection at mouse position: {Input.mousePosition}");
  1104. Debug.Log($"Ray origin: {ray.origin}, Ray direction: {ray.direction}");
  1105. Debug.Log($"Camera: {playerCamera?.name ?? "NULL"}, Camera position: {playerCamera?.transform.position ?? Vector3.zero}");
  1106. Debug.Log($"Total walls in list: {walls.Count}");
  1107. // Check if we have any walls with colliders
  1108. int wallsWithColliders = 0;
  1109. foreach (GameObject wall in walls)
  1110. {
  1111. if (wall != null)
  1112. {
  1113. Collider[] colliders = wall.GetComponentsInChildren<Collider>();
  1114. if (colliders.Length > 0)
  1115. {
  1116. wallsWithColliders++;
  1117. Debug.Log($"Wall {wall.name} has {colliders.Length} colliders");
  1118. }
  1119. }
  1120. }
  1121. Debug.Log($"Walls with colliders: {wallsWithColliders}");
  1122. // Try raycasting with all layers first
  1123. if (Physics.Raycast(ray, out RaycastHit hit, 1000f))
  1124. {
  1125. GameObject hitObj = hit.collider.gameObject;
  1126. Debug.Log($"Raycast hit object: {hitObj.name} on layer {hitObj.layer}");
  1127. Debug.Log($"Hit point: {hit.point}, Hit distance: {hit.distance}");
  1128. // Check if it's one of our walls (could be parent or child)
  1129. GameObject wallToCheck = hitObj;
  1130. // If we hit a child mesh, get the parent
  1131. if (hitObj.name == "WallMesh" && hitObj.transform.parent != null)
  1132. {
  1133. wallToCheck = hitObj.transform.parent.gameObject;
  1134. Debug.Log($"Hit child mesh, checking parent: {wallToCheck.name}");
  1135. }
  1136. if (walls.Contains(wallToCheck))
  1137. {
  1138. Debug.Log($"Hit object is a valid wall: {wallToCheck.name}");
  1139. return wallToCheck;
  1140. }
  1141. else
  1142. {
  1143. Debug.Log($"Hit object is not a wall we created: {wallToCheck.name}");
  1144. // Also check if the hit object has a Wall tag as fallback
  1145. if (hitObj.CompareTag("Wall") || (hitObj.transform.parent != null && hitObj.transform.parent.CompareTag("Wall")))
  1146. {
  1147. GameObject taggedWall = hitObj.CompareTag("Wall") ? hitObj : hitObj.transform.parent.gameObject;
  1148. Debug.Log($"Found wall by tag: {taggedWall.name}");
  1149. return taggedWall;
  1150. }
  1151. }
  1152. }
  1153. else
  1154. {
  1155. Debug.Log("Raycast didn't hit anything - checking for potential issues:");
  1156. Debug.Log($"PlayerCamera null? {playerCamera == null}");
  1157. Debug.Log($"Physics.DefaultRaycastLayers: {Physics.DefaultRaycastLayers}");
  1158. // Try a wider raycast with all layers
  1159. RaycastHit[] hits = Physics.RaycastAll(ray, 1000f);
  1160. Debug.Log($"RaycastAll found {hits.Length} hits");
  1161. for (int i = 0; i < hits.Length; i++)
  1162. {
  1163. Debug.Log($"Hit {i}: {hits[i].collider.gameObject.name} on layer {hits[i].collider.gameObject.layer}");
  1164. }
  1165. }
  1166. return null;
  1167. }
  1168. private GameObject FindWallUnderMouseAlternative(Vector3 worldMousePos)
  1169. {
  1170. // Alternative approach: find the closest wall to the mouse world position
  1171. GameObject closestWall = null;
  1172. float closestDistance = float.MaxValue;
  1173. float maxDistance = 2f; // Maximum distance to consider a wall "under" the mouse
  1174. Debug.Log($"Alternative wall detection at world pos: {worldMousePos}");
  1175. foreach (GameObject wall in walls)
  1176. {
  1177. if (wall == null) continue;
  1178. // Calculate distance from mouse world position to wall center
  1179. float distance = Vector3.Distance(worldMousePos, wall.transform.position);
  1180. // Also check distance to wall bounds
  1181. Bounds wallBounds = GetWallBounds(wall);
  1182. float boundDistance = wallBounds.SqrDistance(worldMousePos);
  1183. Debug.Log($"Wall {wall.name}: center distance = {distance}, bound distance = {Mathf.Sqrt(boundDistance)}");
  1184. if (boundDistance < maxDistance * maxDistance && distance < closestDistance)
  1185. {
  1186. closestDistance = distance;
  1187. closestWall = wall;
  1188. }
  1189. }
  1190. if (closestWall != null)
  1191. {
  1192. Debug.Log($"Alternative method found wall: {closestWall.name} at distance {closestDistance}");
  1193. }
  1194. else
  1195. {
  1196. Debug.Log("Alternative method found no walls nearby");
  1197. }
  1198. return closestWall;
  1199. }
  1200. private Bounds GetWallBounds(GameObject wall)
  1201. {
  1202. Renderer renderer = wall.GetComponentInChildren<Renderer>();
  1203. if (renderer != null)
  1204. {
  1205. return renderer.bounds;
  1206. }
  1207. // Fallback: calculate bounds from transform
  1208. Vector3 scale = wall.transform.localScale;
  1209. return new Bounds(wall.transform.position, scale);
  1210. }
  1211. private GameObject FindNearestWall(Vector3 mousePos)
  1212. {
  1213. GameObject nearestWall = null;
  1214. float nearestDistance = float.MaxValue;
  1215. foreach (GameObject wall in walls)
  1216. {
  1217. if (wall == null) continue;
  1218. // Calculate distance from mouse position to wall
  1219. float distance = Vector3.Distance(mousePos, wall.transform.position);
  1220. if (distance < nearestDistance && distance < 5f) // Within 5 units
  1221. {
  1222. nearestDistance = distance;
  1223. nearestWall = wall;
  1224. }
  1225. }
  1226. if (nearestWall != null)
  1227. {
  1228. Debug.Log($"Found nearest wall: {nearestWall.name} at distance {nearestDistance}");
  1229. }
  1230. return nearestWall;
  1231. }
  1232. private Vector3[] GetWallEndpoints(GameObject wall)
  1233. {
  1234. // Calculate endpoints from wall transform
  1235. Vector3 center = wall.transform.position;
  1236. // With our new rotation, the wall extends along the forward (Z) axis
  1237. Vector3 wallDirection = wall.transform.forward;
  1238. float length = wall.transform.localScale.z; // Z is now the length
  1239. Vector3 start = center - wallDirection * (length / 2f);
  1240. Vector3 end = center + wallDirection * (length / 2f);
  1241. // Ensure Y = 0 for ground-level snapping
  1242. start.y = 0f;
  1243. end.y = 0f;
  1244. return new Vector3[] { start, end };
  1245. }
  1246. private Vector3 CalculateDoorPositionOnWall(GameObject wall, Vector3 mousePos)
  1247. {
  1248. // Project mouse position onto the wall
  1249. Vector3 wallCenter = wall.transform.position;
  1250. Vector3 wallScale = wall.transform.localScale;
  1251. // Determine wall orientation based on scale (not rotation)
  1252. bool isNorthSouthWall = wallScale.x > wallScale.z;
  1253. Vector3 wallDirection;
  1254. float wallLength;
  1255. if (isNorthSouthWall)
  1256. {
  1257. // Wall extends in X direction (North/South wall)
  1258. wallDirection = Vector3.right;
  1259. wallLength = wallScale.x;
  1260. }
  1261. else
  1262. {
  1263. // Wall extends in Z direction (East/West wall)
  1264. wallDirection = Vector3.forward;
  1265. wallLength = wallScale.z;
  1266. }
  1267. // Project mouse onto wall line
  1268. Vector3 toMouse = mousePos - wallCenter;
  1269. float projection = Vector3.Dot(toMouse, wallDirection);
  1270. // Clamp to wall bounds
  1271. projection = Mathf.Clamp(projection, -wallLength / 2f + doorWidth / 2f, wallLength / 2f - doorWidth / 2f);
  1272. Vector3 doorPos = wallCenter + wallDirection * projection;
  1273. doorPos.y = 0f; // Set door at ground level
  1274. Debug.Log($"Door position calculation: wallCenter={wallCenter}, wallDirection={wallDirection}, projection={projection}, doorPos={doorPos}");
  1275. return doorPos;
  1276. }
  1277. #endregion
  1278. }