NewRoomBuilder.cs 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622
  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; // Set rotation based on wall orientation
  831. if (isNorthSouthWall)
  832. {
  833. // For North/South walls (extending in X), entrance should face along Z-axis
  834. entrance.transform.rotation = Quaternion.identity; // Facing forward (positive Z)
  835. }
  836. else
  837. {
  838. // For East/West walls (extending in Z), entrance should face along X-axis
  839. entrance.transform.rotation = Quaternion.Euler(0, 90, 0); // Facing right (positive X)
  840. }
  841. entrance.SetActive(true);
  842. entrance.name = "BuildingEntrance";
  843. entrance.tag = "Entrance";
  844. Debug.Log($"Placed entrance at {entrance.transform.position} with rotation {entrance.transform.rotation.eulerAngles}");
  845. // Split the wall properly based on its orientation
  846. SplitWallForEntrance(wall, entrancePosition, entranceWidth, isNorthSouthWall);
  847. Debug.Log($"Successfully placed entrance and split wall");
  848. }
  849. private void SplitWallForEntrance(GameObject originalWall, Vector3 entrancePosition, float entranceWidth, bool isNorthSouthWall)
  850. {
  851. Vector3 wallPos = originalWall.transform.position;
  852. Vector3 wallScale = originalWall.transform.localScale;
  853. Quaternion wallRotation = originalWall.transform.rotation;
  854. // Get the original wall's material to maintain consistency
  855. Material originalMaterial = originalWall.GetComponent<Renderer>()?.material;
  856. if (wallPrefab == null)
  857. {
  858. Debug.LogError("WallPrefab is null! Cannot create wall segments. Aborting split operation.");
  859. return;
  860. }
  861. if (isNorthSouthWall)
  862. {
  863. // Wall extends in X direction, split along X-axis
  864. float wallLength = wallScale.x; // Corrected: X is the length for North/South walls
  865. float wallLeft = wallPos.x - wallLength / 2f;
  866. float wallRight = wallPos.x + wallLength / 2f;
  867. float entranceLeft = entrancePosition.x - entranceWidth / 2f;
  868. float entranceRight = entrancePosition.x + entranceWidth / 2f;
  869. Debug.Log($"North/South wall split: wallLeft={wallLeft}, wallRight={wallRight}, entranceLeft={entranceLeft}, entranceRight={entranceRight}");
  870. float leftSegmentLength = entranceLeft - wallLeft;
  871. float rightSegmentLength = wallRight - entranceRight;
  872. Debug.Log($"Segment lengths: left={leftSegmentLength}, right={rightSegmentLength}"); // Create left segment if there's enough space
  873. if (leftSegmentLength > 0.5f)
  874. {
  875. Vector3 leftCenter = new Vector3(wallLeft + leftSegmentLength / 2f, wallPos.y, wallPos.z);
  876. GameObject leftWall = Instantiate(wallPrefab, leftCenter, wallRotation);
  877. leftWall.SetActive(true);
  878. leftWall.name = $"{originalWall.name}_Left_Entrance";
  879. leftWall.transform.localScale = new Vector3(leftSegmentLength, wallScale.y, wallScale.z);
  880. leftWall.tag = "Wall";
  881. // Apply original material if available, with error checking
  882. if (originalMaterial != null)
  883. {
  884. Renderer leftRenderer = leftWall.GetComponent<Renderer>();
  885. if (leftRenderer != null)
  886. {
  887. leftRenderer.material = originalMaterial;
  888. Debug.Log($"Applied original material to left wall segment");
  889. }
  890. else
  891. {
  892. Debug.LogWarning($"Left wall segment {leftWall.name} has no Renderer component - cannot apply material");
  893. }
  894. }
  895. walls.Add(leftWall);
  896. Debug.Log($"SUCCESS: Created left wall segment: {leftWall.name}");
  897. }
  898. else
  899. {
  900. Debug.Log($"LEFT SEGMENT TOO SMALL: {leftSegmentLength} <= 0.5f, not creating");
  901. }
  902. // Create right segment if there's enough space
  903. if (rightSegmentLength > 0.5f)
  904. {
  905. Vector3 rightCenter = new Vector3(entranceRight + rightSegmentLength / 2f, wallPos.y, wallPos.z);
  906. GameObject rightWall = Instantiate(wallPrefab, rightCenter, wallRotation);
  907. rightWall.SetActive(true);
  908. rightWall.name = $"{originalWall.name}_Right_Entrance";
  909. rightWall.transform.localScale = new Vector3(rightSegmentLength, wallScale.y, wallScale.z);
  910. rightWall.tag = "Wall";
  911. // Apply original material if available, with error checking
  912. if (originalMaterial != null)
  913. {
  914. Renderer rightRenderer = rightWall.GetComponent<Renderer>();
  915. if (rightRenderer != null)
  916. {
  917. rightRenderer.material = originalMaterial;
  918. Debug.Log($"Applied original material to right wall segment");
  919. }
  920. else
  921. {
  922. Debug.LogWarning($"Right wall segment {rightWall.name} has no Renderer component - cannot apply material");
  923. }
  924. }
  925. walls.Add(rightWall);
  926. Debug.Log($"SUCCESS: Created right wall segment: {rightWall.name}");
  927. }
  928. else
  929. {
  930. Debug.Log($"RIGHT SEGMENT TOO SMALL: {rightSegmentLength} <= 0.5f, not creating");
  931. }
  932. }
  933. else
  934. {
  935. // Wall extends in Z direction, split along Z-axis
  936. float wallLength = wallScale.z;
  937. float wallFront = wallPos.z - wallLength / 2f;
  938. float wallBack = wallPos.z + wallLength / 2f;
  939. float entranceFront = entrancePosition.z - entranceWidth / 2f;
  940. float entranceBack = entrancePosition.z + entranceWidth / 2f;
  941. Debug.Log($"East/West wall split: wallFront={wallFront}, wallBack={wallBack}, entranceFront={entranceFront}, entranceBack={entranceBack}");
  942. float frontSegmentLength = entranceFront - wallFront;
  943. float backSegmentLength = wallBack - entranceBack;
  944. Debug.Log($"Segment lengths: front={frontSegmentLength}, back={backSegmentLength}"); // Create front segment if there's enough space
  945. if (frontSegmentLength > 0.5f)
  946. {
  947. Vector3 frontCenter = new Vector3(wallPos.x, wallPos.y, wallFront + frontSegmentLength / 2f);
  948. Debug.Log($"Creating front segment at {frontCenter} with scale ({wallScale.x}, {wallScale.y}, {frontSegmentLength})");
  949. GameObject frontWall = Instantiate(wallPrefab, frontCenter, wallRotation);
  950. frontWall.SetActive(true);
  951. frontWall.name = $"{originalWall.name}_Front_Entrance";
  952. frontWall.transform.localScale = new Vector3(wallScale.x, wallScale.y, frontSegmentLength);
  953. frontWall.tag = "Wall";
  954. // Apply original material if available, with error checking
  955. if (originalMaterial != null)
  956. {
  957. Renderer frontRenderer = frontWall.GetComponent<Renderer>();
  958. if (frontRenderer != null)
  959. {
  960. frontRenderer.material = originalMaterial;
  961. Debug.Log($"Applied original material to front wall segment");
  962. }
  963. else
  964. {
  965. Debug.LogWarning($"Front wall segment {frontWall.name} has no Renderer component - cannot apply material");
  966. }
  967. }
  968. walls.Add(frontWall);
  969. Debug.Log($"SUCCESS: Created front wall segment: {frontWall.name}");
  970. }
  971. else
  972. {
  973. Debug.Log($"FRONT SEGMENT TOO SMALL: {frontSegmentLength} <= 0.5f, not creating");
  974. }
  975. // Create back segment if there's enough space
  976. if (backSegmentLength > 0.5f)
  977. {
  978. Vector3 backCenter = new Vector3(wallPos.x, wallPos.y, entranceBack + backSegmentLength / 2f);
  979. Debug.Log($"Creating back segment at {backCenter} with scale ({wallScale.x}, {wallScale.y}, {backSegmentLength})");
  980. GameObject backWall = Instantiate(wallPrefab, backCenter, wallRotation);
  981. backWall.SetActive(true);
  982. backWall.name = $"{originalWall.name}_Back_Entrance";
  983. backWall.transform.localScale = new Vector3(wallScale.x, wallScale.y, backSegmentLength);
  984. backWall.tag = "Wall";
  985. // Apply original material if available, with error checking
  986. if (originalMaterial != null)
  987. {
  988. Renderer backRenderer = backWall.GetComponent<Renderer>();
  989. if (backRenderer != null)
  990. {
  991. backRenderer.material = originalMaterial;
  992. Debug.Log($"Applied original material to back wall segment");
  993. }
  994. else
  995. {
  996. Debug.LogWarning($"Back wall segment {backWall.name} has no Renderer component - cannot apply material");
  997. }
  998. }
  999. walls.Add(backWall);
  1000. Debug.Log($"SUCCESS: Created back wall segment: {backWall.name}");
  1001. }
  1002. else
  1003. {
  1004. Debug.Log($"BACK SEGMENT TOO SMALL: {backSegmentLength} <= 0.5f, not creating");
  1005. }
  1006. }
  1007. // Remove original wall
  1008. Debug.Log($"REMOVING ORIGINAL WALL: {originalWall.name} (active: {originalWall.activeInHierarchy})");
  1009. walls.Remove(originalWall);
  1010. // Try multiple removal methods to ensure it's gone
  1011. originalWall.SetActive(false);
  1012. DestroyImmediate(originalWall);
  1013. Debug.Log("Original wall removal completed");
  1014. }
  1015. private GameObject CreateEntrancePrefab()
  1016. {
  1017. // Create a more elaborate entrance than a regular door
  1018. GameObject entrance = new GameObject("BuildingEntrance");
  1019. // Create entrance frame - wider and more elaborate
  1020. GameObject entranceFrame = new GameObject("EntranceFrame");
  1021. entranceFrame.transform.SetParent(entrance.transform);
  1022. float entranceWidth = doorWidth * 1.5f;
  1023. // Create frame components: left post, right post, top beam, and entrance mat
  1024. CreateEntrancePost(entranceFrame, "LeftPost", new Vector3(-entranceWidth / 2f, doorHeight / 2f, 0f), entranceWidth);
  1025. CreateEntrancePost(entranceFrame, "RightPost", new Vector3(entranceWidth / 2f, doorHeight / 2f, 0f), entranceWidth);
  1026. CreateEntranceBeam(entranceFrame, "TopBeam", new Vector3(0f, doorHeight - 0.1f, 0f), entranceWidth);
  1027. CreateEntranceMat(entranceFrame, "WelcomeMat", new Vector3(0f, 0.05f, 1f), entranceWidth);
  1028. entrance.tag = "Entrance";
  1029. DontDestroyOnLoad(entrance);
  1030. return entrance;
  1031. }
  1032. private void CreateEntrancePost(GameObject parent, string name, Vector3 position, float width)
  1033. {
  1034. GameObject post = GameObject.CreatePrimitive(PrimitiveType.Cube);
  1035. post.name = name;
  1036. post.transform.SetParent(parent.transform);
  1037. post.transform.localPosition = position;
  1038. post.transform.localScale = new Vector3(0.15f, doorHeight, 0.3f); // Slightly thicker than door posts
  1039. Renderer renderer = post.GetComponent<Renderer>();
  1040. Material frameMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  1041. frameMaterial.color = new Color(0.3f, 0.15f, 0.05f); // Darker brown for entrance
  1042. frameMaterial.SetFloat("_Metallic", 0.0f);
  1043. frameMaterial.SetFloat("_Smoothness", 0.4f);
  1044. renderer.material = frameMaterial;
  1045. }
  1046. private void CreateEntranceBeam(GameObject parent, string name, Vector3 position, float width)
  1047. {
  1048. GameObject beam = GameObject.CreatePrimitive(PrimitiveType.Cube);
  1049. beam.name = name;
  1050. beam.transform.SetParent(parent.transform);
  1051. beam.transform.localPosition = position;
  1052. beam.transform.localScale = new Vector3(width + 0.3f, 0.3f, 0.3f); // Wider and thicker beam
  1053. Renderer renderer = beam.GetComponent<Renderer>();
  1054. Material frameMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  1055. frameMaterial.color = new Color(0.3f, 0.15f, 0.05f); // Darker brown for entrance
  1056. frameMaterial.SetFloat("_Metallic", 0.0f);
  1057. frameMaterial.SetFloat("_Smoothness", 0.4f);
  1058. renderer.material = frameMaterial;
  1059. }
  1060. private void CreateEntranceMat(GameObject parent, string name, Vector3 position, float width)
  1061. {
  1062. GameObject mat = GameObject.CreatePrimitive(PrimitiveType.Cube);
  1063. mat.name = name;
  1064. mat.transform.SetParent(parent.transform);
  1065. mat.transform.localPosition = position;
  1066. mat.transform.localScale = new Vector3(width, 0.1f, 1.5f); // Welcome mat dimensions
  1067. Renderer renderer = mat.GetComponent<Renderer>();
  1068. Material matMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  1069. matMaterial.color = new Color(0.8f, 0.2f, 0.2f); // Red welcome mat
  1070. matMaterial.SetFloat("_Metallic", 0.0f);
  1071. matMaterial.SetFloat("_Smoothness", 0.1f); // Rough mat texture
  1072. renderer.material = matMaterial;
  1073. }
  1074. #endregion
  1075. #region Helper Methods
  1076. private void CreatePreviewLine()
  1077. {
  1078. GameObject previewObj = new GameObject("WallPreview");
  1079. previewLine = previewObj.AddComponent<LineRenderer>();
  1080. // Use URP Unlit shader for line renderer (better for simple colored lines)
  1081. previewLine.material = new Material(Shader.Find("Universal Render Pipeline/Unlit"));
  1082. previewLine.material.color = Color.yellow;
  1083. previewLine.startColor = Color.yellow;
  1084. previewLine.endColor = Color.yellow;
  1085. previewLine.startWidth = 0.1f;
  1086. previewLine.endWidth = 0.1f;
  1087. previewLine.positionCount = 2;
  1088. previewLine.enabled = false;
  1089. }
  1090. private void CreateDoorPreview()
  1091. {
  1092. // Create a simple preview object
  1093. doorPreview = GameObject.CreatePrimitive(PrimitiveType.Cube);
  1094. doorPreview.name = "DoorPreview";
  1095. // Make it transparent green
  1096. Renderer renderer = doorPreview.GetComponent<Renderer>();
  1097. Material previewMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  1098. // Set up bright green transparent color
  1099. previewMaterial.color = new Color(0f, 1f, 0f, 0.6f); // Bright transparent green
  1100. // Set up transparency properly for URP
  1101. previewMaterial.SetFloat("_Surface", 1); // Set to Transparent
  1102. previewMaterial.SetFloat("_Blend", 0); // Alpha blend
  1103. previewMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
  1104. previewMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
  1105. previewMaterial.SetInt("_ZWrite", 0);
  1106. previewMaterial.renderQueue = 3000;
  1107. // Make it non-metallic and smooth for better visibility
  1108. previewMaterial.SetFloat("_Metallic", 0.0f);
  1109. previewMaterial.SetFloat("_Smoothness", 0.9f);
  1110. renderer.material = previewMaterial;
  1111. // Scale to door size - match the actual door dimensions
  1112. doorPreview.transform.localScale = new Vector3(0.2f, doorHeight, doorWidth);
  1113. doorPreview.SetActive(false);
  1114. // Remove collider to prevent interference
  1115. Collider collider = doorPreview.GetComponent<Collider>();
  1116. if (collider != null) Destroy(collider);
  1117. }
  1118. private void CreateSnapIndicator()
  1119. {
  1120. snapIndicator = GameObject.CreatePrimitive(PrimitiveType.Sphere);
  1121. snapIndicator.name = "SnapIndicator";
  1122. // Make it a bright, pulsing indicator
  1123. Renderer renderer = snapIndicator.GetComponent<Renderer>();
  1124. Material indicatorMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
  1125. indicatorMaterial.color = Color.cyan;
  1126. indicatorMaterial.SetFloat("_Metallic", 0.0f);
  1127. indicatorMaterial.SetFloat("_Smoothness", 0.9f);
  1128. // Make it emissive so it glows
  1129. indicatorMaterial.EnableKeyword("_EMISSION");
  1130. indicatorMaterial.SetColor("_EmissionColor", Color.cyan * 2f);
  1131. renderer.material = indicatorMaterial;
  1132. // Scale it to be visible but not too large
  1133. snapIndicator.transform.localScale = Vector3.one * 0.3f;
  1134. snapIndicator.SetActive(false);
  1135. // Remove collider to prevent interference
  1136. Collider collider = snapIndicator.GetComponent<Collider>();
  1137. if (collider != null) Destroy(collider);
  1138. }
  1139. private void HideAllPreviews()
  1140. {
  1141. if (previewLine != null)
  1142. {
  1143. previewLine.enabled = false;
  1144. }
  1145. HideDoorPreview();
  1146. HideSnapIndicator();
  1147. }
  1148. private Vector3 GetMouseWorldPosition()
  1149. {
  1150. Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);
  1151. // Cast ray onto ground plane (Y = 0)
  1152. if (Physics.Raycast(ray, out RaycastHit hit))
  1153. {
  1154. return hit.point;
  1155. }
  1156. // Fallback: project onto Y = 0 plane
  1157. float distance = -ray.origin.y / ray.direction.y;
  1158. return ray.origin + ray.direction * distance;
  1159. }
  1160. private GameObject FindWallUnderMouse(Vector3 mousePos)
  1161. {
  1162. Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);
  1163. Debug.Log($"Raycasting for wall detection at mouse position: {Input.mousePosition}");
  1164. Debug.Log($"Ray origin: {ray.origin}, Ray direction: {ray.direction}");
  1165. Debug.Log($"Camera: {playerCamera?.name ?? "NULL"}, Camera position: {playerCamera?.transform.position ?? Vector3.zero}");
  1166. Debug.Log($"Total walls in list: {walls.Count}");
  1167. // Check if we have any walls with colliders
  1168. int wallsWithColliders = 0;
  1169. foreach (GameObject wall in walls)
  1170. {
  1171. if (wall != null)
  1172. {
  1173. Collider[] colliders = wall.GetComponentsInChildren<Collider>();
  1174. if (colliders.Length > 0)
  1175. {
  1176. wallsWithColliders++;
  1177. Debug.Log($"Wall {wall.name} has {colliders.Length} colliders");
  1178. }
  1179. }
  1180. }
  1181. Debug.Log($"Walls with colliders: {wallsWithColliders}");
  1182. // Try raycasting with all layers first
  1183. if (Physics.Raycast(ray, out RaycastHit hit, 1000f))
  1184. {
  1185. GameObject hitObj = hit.collider.gameObject;
  1186. Debug.Log($"Raycast hit object: {hitObj.name} on layer {hitObj.layer}");
  1187. Debug.Log($"Hit point: {hit.point}, Hit distance: {hit.distance}");
  1188. // Check if it's one of our walls (could be parent or child)
  1189. GameObject wallToCheck = hitObj;
  1190. // If we hit a child mesh, get the parent
  1191. if (hitObj.name == "WallMesh" && hitObj.transform.parent != null)
  1192. {
  1193. wallToCheck = hitObj.transform.parent.gameObject;
  1194. Debug.Log($"Hit child mesh, checking parent: {wallToCheck.name}");
  1195. }
  1196. if (walls.Contains(wallToCheck))
  1197. {
  1198. Debug.Log($"Hit object is a valid wall: {wallToCheck.name}");
  1199. return wallToCheck;
  1200. }
  1201. else
  1202. {
  1203. Debug.Log($"Hit object is not a wall we created: {wallToCheck.name}");
  1204. // Also check if the hit object has a Wall tag as fallback
  1205. if (hitObj.CompareTag("Wall") || (hitObj.transform.parent != null && hitObj.transform.parent.CompareTag("Wall")))
  1206. {
  1207. GameObject taggedWall = hitObj.CompareTag("Wall") ? hitObj : hitObj.transform.parent.gameObject;
  1208. Debug.Log($"Found wall by tag: {taggedWall.name}");
  1209. return taggedWall;
  1210. }
  1211. }
  1212. }
  1213. else
  1214. {
  1215. Debug.Log("Raycast didn't hit anything - checking for potential issues:");
  1216. Debug.Log($"PlayerCamera null? {playerCamera == null}");
  1217. Debug.Log($"Physics.DefaultRaycastLayers: {Physics.DefaultRaycastLayers}");
  1218. // Try a wider raycast with all layers
  1219. RaycastHit[] hits = Physics.RaycastAll(ray, 1000f);
  1220. Debug.Log($"RaycastAll found {hits.Length} hits");
  1221. for (int i = 0; i < hits.Length; i++)
  1222. {
  1223. Debug.Log($"Hit {i}: {hits[i].collider.gameObject.name} on layer {hits[i].collider.gameObject.layer}");
  1224. }
  1225. }
  1226. return null;
  1227. }
  1228. private GameObject FindWallUnderMouseAlternative(Vector3 worldMousePos)
  1229. {
  1230. // Alternative approach: find the closest wall to the mouse world position
  1231. GameObject closestWall = null;
  1232. float closestDistance = float.MaxValue;
  1233. float maxDistance = 2f; // Maximum distance to consider a wall "under" the mouse
  1234. Debug.Log($"Alternative wall detection at world pos: {worldMousePos}");
  1235. foreach (GameObject wall in walls)
  1236. {
  1237. if (wall == null) continue;
  1238. // Calculate distance from mouse world position to wall center
  1239. float distance = Vector3.Distance(worldMousePos, wall.transform.position);
  1240. // Also check distance to wall bounds
  1241. Bounds wallBounds = GetWallBounds(wall);
  1242. float boundDistance = wallBounds.SqrDistance(worldMousePos);
  1243. Debug.Log($"Wall {wall.name}: center distance = {distance}, bound distance = {Mathf.Sqrt(boundDistance)}");
  1244. if (boundDistance < maxDistance * maxDistance && distance < closestDistance)
  1245. {
  1246. closestDistance = distance;
  1247. closestWall = wall;
  1248. }
  1249. }
  1250. if (closestWall != null)
  1251. {
  1252. Debug.Log($"Alternative method found wall: {closestWall.name} at distance {closestDistance}");
  1253. }
  1254. else
  1255. {
  1256. Debug.Log("Alternative method found no walls nearby");
  1257. }
  1258. return closestWall;
  1259. }
  1260. private Bounds GetWallBounds(GameObject wall)
  1261. {
  1262. Renderer renderer = wall.GetComponentInChildren<Renderer>();
  1263. if (renderer != null)
  1264. {
  1265. return renderer.bounds;
  1266. }
  1267. // Fallback: calculate bounds from transform
  1268. Vector3 scale = wall.transform.localScale;
  1269. return new Bounds(wall.transform.position, scale);
  1270. }
  1271. private GameObject FindNearestWall(Vector3 mousePos)
  1272. {
  1273. GameObject nearestWall = null;
  1274. float nearestDistance = float.MaxValue;
  1275. foreach (GameObject wall in walls)
  1276. {
  1277. if (wall == null) continue;
  1278. // Calculate distance from mouse position to wall
  1279. float distance = Vector3.Distance(mousePos, wall.transform.position);
  1280. if (distance < nearestDistance && distance < 5f) // Within 5 units
  1281. {
  1282. nearestDistance = distance;
  1283. nearestWall = wall;
  1284. }
  1285. }
  1286. if (nearestWall != null)
  1287. {
  1288. Debug.Log($"Found nearest wall: {nearestWall.name} at distance {nearestDistance}");
  1289. }
  1290. return nearestWall;
  1291. }
  1292. private Vector3[] GetWallEndpoints(GameObject wall)
  1293. {
  1294. // Calculate endpoints from wall transform
  1295. Vector3 center = wall.transform.position;
  1296. // With our new rotation, the wall extends along the forward (Z) axis
  1297. Vector3 wallDirection = wall.transform.forward;
  1298. float length = wall.transform.localScale.z; // Z is now the length
  1299. Vector3 start = center - wallDirection * (length / 2f);
  1300. Vector3 end = center + wallDirection * (length / 2f);
  1301. // Ensure Y = 0 for ground-level snapping
  1302. start.y = 0f;
  1303. end.y = 0f;
  1304. return new Vector3[] { start, end };
  1305. }
  1306. private Vector3 CalculateDoorPositionOnWall(GameObject wall, Vector3 mousePos)
  1307. {
  1308. // Project mouse position onto the wall
  1309. Vector3 wallCenter = wall.transform.position;
  1310. Vector3 wallScale = wall.transform.localScale;
  1311. // Use the wall's actual transform directions instead of world axes
  1312. Vector3 wallDirection;
  1313. float wallLength;
  1314. // Determine wall orientation based on scale
  1315. bool isNorthSouthWall = wallScale.x > wallScale.z;
  1316. if (isNorthSouthWall)
  1317. {
  1318. // Wall extends in X direction - use the wall's right vector (local X axis)
  1319. wallDirection = wall.transform.right;
  1320. wallLength = wallScale.x;
  1321. }
  1322. else
  1323. {
  1324. // Wall extends in Z direction - use the wall's forward vector (local Z axis)
  1325. wallDirection = wall.transform.forward;
  1326. wallLength = wallScale.z;
  1327. }
  1328. // Project mouse position onto the wall's direction vector
  1329. Vector3 toMouse = mousePos - wallCenter;
  1330. float projection = Vector3.Dot(toMouse, wallDirection);
  1331. // Clamp to wall bounds
  1332. float clampedProjection = Mathf.Clamp(projection, -wallLength / 2f + doorWidth / 2f, wallLength / 2f - doorWidth / 2f);
  1333. Vector3 doorPos = wallCenter + wallDirection * clampedProjection;
  1334. doorPos.y = 0f; // Set door at ground level
  1335. return doorPos;
  1336. }
  1337. #endregion
  1338. }