diff --git a/Assets/Scripts/GameBase/BuildManager.cs b/Assets/Scripts/GameBase/BuildManager.cs index ef16894..d1ec43d 100644 --- a/Assets/Scripts/GameBase/BuildManager.cs +++ b/Assets/Scripts/GameBase/BuildManager.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; public class BuildManager : MonoBehaviour { public static BuildManager Instance; - + [System.Serializable] public struct TurretData { @@ -29,7 +29,7 @@ public class BuildManager : MonoBehaviour [SerializeField] private TurretData selectedTurret; // 현재 선택된 타워 데이터 [SerializeField] private bool isBuildMode = false; - [SerializeField] private LayerMask playerLayer; // 플레이어의 레이어를 지정하세요. + [SerializeField] private LayerMask playerLayer; // 플레이어의 레이어 [Header("Turret Library")] [SerializeField] private List turretLibrary; // 인스펙터에서 여러 타워 등록 @@ -70,20 +70,21 @@ public class BuildManager : MonoBehaviour Vector2Int gridPos = WorldToGrid(hit.point); _ghostInstance.transform.position = GridToWorld(gridPos, selectedTurret.size); - // 건설 가능 여부 실시간 체크 - bool canPlace = CanBuild(gridPos, selectedTurret.size); + // [수정] CanBuild 호출 인자를 selectedTurret 전체로 변경 + bool canPlace = CanBuild(gridPos, selectedTurret); - // 고스트 색상 변경 (Material의 _Color 속성이 있다고 가정) + // 고스트 색상 변경 if (_ghostMaterial != null) { _ghostMaterial.color = canPlace ? new Color(0, 1, 0, 0.5f) : new Color(1, 0, 0, 0.5f); } - // 미리보기 타워의 사거리 표시기를 켭니다. + // 미리보기 타워의 사거리 표시기 제어 TowerRangeOverlay overlay = _ghostInstance.GetComponentInChildren(); if (overlay != null) { overlay.ShowRange(true); + overlay.UpdateRangeScale(); // 매 프레임 스케일 보정 } } } @@ -105,7 +106,8 @@ public class BuildManager : MonoBehaviour if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, groundLayer)) { Vector2Int gridPos = WorldToGrid(hit.point); - if (CanBuild(gridPos, selectedTurret.size)) + // [수정] CanBuild 호출 인자 변경 + if (CanBuild(gridPos, selectedTurret)) { Build(gridPos, selectedTurret); } @@ -128,85 +130,54 @@ public class BuildManager : MonoBehaviour _ghostInstance = Instantiate(selectedTurret.ghostPrefab); - // 1. 스케일 먼저 조절 + // 고스트의 머티리얼 참조 (색상 변경용) + Renderer ghostRenderer = _ghostInstance.GetComponentInChildren(); + if (ghostRenderer != null) _ghostMaterial = ghostRenderer.material; + + // 1. 비주얼 스케일 조절 Transform visual = _ghostInstance.transform.Find("Visual"); if (visual != null) { visual.localScale = new Vector3(selectedTurret.size.x, 1f, selectedTurret.size.y); } - // 2. 그 다음 바닥 정렬 호출 (yOffset은 데이터에서 가져오거나 0 전달) + // 2. 바닥 정렬 AlignToGround(_ghostInstance, 0f); } private void DestroyGhost() { if (_ghostInstance != null) Destroy(_ghostInstance); - } - - private void UpdateGhost() - { - if (_ghostInstance == null) return; - - Vector2 mousePos = Mouse.current.position.ReadValue(); - Ray ray = Camera.main.ScreenPointToRay(mousePos); - - if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, groundLayer)) - { - _ghostInstance.SetActive(true); - Vector2Int gridPos = WorldToGrid(hit.point); - _ghostInstance.transform.position = GridToWorld(gridPos, selectedTurret.size); - - bool canBuild = CanBuild(gridPos, selectedTurret.size); - _ghostMaterial.color = canBuild ? new Color(0, 1, 0, 0.5f) : new Color(1, 0, 0, 0.5f); - } - else - { - _ghostInstance.SetActive(false); - } + _ghostMaterial = null; } private void Build(Vector2Int gridPos, TurretData data) { - // 1. 프리팹 할당 여부 체크 - if (constructionSitePrefab == null) + if (constructionSitePrefab == null || data.finalPrefab == null) { - Debug.LogError("BuildManager: Construction Site Prefab이 할당되지 않았습니다!"); + Debug.LogError("BuildManager: 프리팹 할당 상태를 확인하세요!"); return; } - if (data.finalPrefab == null) - { - Debug.LogError($"BuildManager: {data.turretName}의 Final Prefab이 할당되지 않았습니다!"); - return; - } - - // 2. 점유 노드 등록 + // 점유 노드 등록 for (int x = 0; x < data.size.x; x++) for (int y = 0; y < data.size.y; y++) _occupiedNodes.Add(new Vector2Int(gridPos.x + x, gridPos.y + y)); - // 3. 토대 생성 (위치는 GridToWorld로 정확히 잡되, 스케일은 건드리지 않음) + // 토대 생성 GameObject siteObj = Instantiate(constructionSitePrefab, GridToWorld(gridPos, data.size), Quaternion.identity); - // [수정] 최상단 siteObj 대신 자식인 "Visual"의 크기만 조절 + // 토대 비주얼 스케일 조절 Transform visual = siteObj.transform.Find("Visual"); if (visual != null) { visual.localScale = new Vector3(data.size.x, 1f, data.size.y); } - else - { - // 만약 Visual 오브젝트를 못 찾았다면, 개발 중 실수를 방지하기 위해 경고를 띄웁니다. - Debug.LogWarning("BuildManager: 토대 프리팹에서 'Visual' 자식을 찾을 수 없습니다."); - // 차선책으로 전체를 키움 (기존 로직) - siteObj.transform.localScale = new Vector3(data.size.x, 1f, data.size.y); - } // 토대 바닥 정렬 AlignToGround(siteObj, 0f); - // 4. 컴포넌트 초기화 + // 컴포넌트 초기화 ConstructionSite siteScript = siteObj.GetComponent(); if (siteScript != null) { @@ -219,11 +190,22 @@ public class BuildManager : MonoBehaviour // --- Utilities --- private bool CanBuild(Vector2Int startPos, TurretData data) { - // 1. 기존 점유 노드 및 플레이어 충돌 체크 (기존 로직) + // 1. 기존 점유 노드 및 플레이어 충돌 체크 for (int x = 0; x < data.size.x; x++) + { for (int y = 0; y < data.size.y; y++) + { if (_occupiedNodes.Contains(new Vector2Int(startPos.x + x, startPos.y + y))) return false; + } + } + + // 플레이어와 겹치는지 체크 + Vector3 center = GridToWorld(startPos, data.size); + center.y = 1f; + Vector3 halfExtents = new Vector3(data.size.x * 0.45f, 0.5f, data.size.y * 0.45f); + if (Physics.CheckBox(center, halfExtents, Quaternion.identity, playerLayer)) + return false; // 2. 터널 연결 제약 조건 체크 if (data.isTunnel) @@ -231,34 +213,52 @@ public class BuildManager : MonoBehaviour return IsConnectedToExistingTunnel(startPos, data); } - return true; // 일반 타워는 어디든 건설 가능 (필요시 수정) + return true; } private bool IsConnectedToExistingTunnel(Vector2Int startPos, TurretData data) { - // [중요] 게임의 첫 번째 터널을 지을 수 있도록, 기존 터널이 아예 없다면 true 반환 - // 혹은 '코어(성벽)' 레이어를 체크하도록 할 수도 있습니다. + // 첫 번째 터널은 자유롭게 설치 (또는 특정 구역 제한) if (_occupiedNodes.Count == 0) return true; - // 현재 배치하려는 고스트의 위치 근처에 이미 완성된 TunnelNode가 있는지 검사합니다. Vector3 ghostWorldPos = GridToWorld(startPos, data.size); - - // 고스트 프리팹에 있는 노드들의 상대 위치를 활용해 주변을 검색합니다. - // 여기서는 간단하게 고스트의 일정 반경 내에 Tunnel 레이어가 있는지 확인합니다. - float checkRadius = cellSize * 1.5f; // 한 칸 정도의 여유 범위 + float checkRadius = cellSize * 1.5f; Collider[] neighbors = Physics.OverlapSphere(ghostWorldPos, checkRadius, LayerMask.GetMask("Tunnel")); foreach (var col in neighbors) { - // 건설 중인 '토대'가 아니라, 이미 '완공된' 터널 노드인지 확인해야 합니다. TunnelNode node = col.GetComponent(); if (node != null && node.gameObject.activeInHierarchy) { - return true; // 연결 가능한 노드 발견! + return true; } } + return false; + } - return false; // 주변에 연결된 터널이 없음 + public Vector2Int WorldToGrid(Vector3 worldPos) => new Vector2Int(Mathf.FloorToInt(worldPos.x / cellSize), Mathf.FloorToInt(worldPos.z / cellSize)); + + public Vector3 GridToWorld(Vector2Int gridPos, Vector2Int size) + { + return new Vector3(gridPos.x * cellSize + (size.x - 1) * cellSize * 0.5f, 0.05f, gridPos.y * cellSize + (size.y - 1) * cellSize * 0.5f); + } + + public void AlignToGround(GameObject obj, float yOffset) + { + Transform visual = obj.transform.Find("Visual"); + if (visual == null) return; + + MeshRenderer[] renderers = visual.GetComponentsInChildren(); + if (renderers.Length == 0) return; + + Bounds bounds = renderers[0].bounds; + foreach (var renderer in renderers) + { + bounds.Encapsulate(renderer.bounds); + } + + float bottomY = bounds.min.y - obj.transform.position.y; + visual.localPosition = new Vector3(0, -bottomY + yOffset, 0); } private void OnDrawGizmos() @@ -269,39 +269,12 @@ public class BuildManager : MonoBehaviour Gizmos.DrawWireCube(new Vector3(x * cellSize, 0, z * cellSize), new Vector3(cellSize, 0.01f, cellSize)); } - // 현재 선택된 타워를 변경하는 공용 메서드 public void SelectTurret(int index) { if (index >= 0 && index < turretLibrary.Count) { selectedTurret = turretLibrary[index]; - Debug.Log($"{selectedTurret.turretName} 선택됨!"); - - // 만약 건설 모드 중이라면 고스트도 즉시 교체 - if (isBuildMode) - { - CreateGhost(); - } + if (isBuildMode) CreateGhost(); } } - - private void AlignToGround(GameObject obj, float yOffset) - { - Transform visual = obj.transform.Find("Visual"); - if (visual == null) return; - - // Visual 자식 아래에 있는 모든 MeshRenderer를 찾아서 전체 범위를 계산 - MeshRenderer[] renderers = visual.GetComponentsInChildren(); - if (renderers.Length == 0) return; - - Bounds bounds = renderers[0].bounds; - foreach (var renderer in renderers) - { - bounds.Encapsulate(renderer.bounds); - } - - // 모델의 가장 바닥(bounds.min.y)이 0이 되도록 차이만큼 올려줌 - float bottomY = bounds.min.y - obj.transform.position.y; - visual.localPosition = new Vector3(0, -bottomY + yOffset, 0); - } } \ No newline at end of file diff --git a/Assets/Scripts/Tower/ConstructionSite.cs b/Assets/Scripts/Tower/ConstructionSite.cs index 1c7acdd..540b835 100644 --- a/Assets/Scripts/Tower/ConstructionSite.cs +++ b/Assets/Scripts/Tower/ConstructionSite.cs @@ -1,23 +1,23 @@ using UnityEngine; -using UnityEngine.UI; // UI 사용을 위해 추가 +using UnityEngine.UI; public class ConstructionSite : MonoBehaviour { [Header("UI Settings")] - [SerializeField] private GameObject uiPrefab; // 방금 만든 Canvas 프리팹 + [SerializeField] private GameObject uiPrefab; // Canvas 프리팹 [SerializeField] private Vector3 uiOffset = new Vector3(0, 2f, 0); // 머리 위 높이 private Slider _progressSlider; - private GameObject _finalTurretPrefab; + private GameObject _finalPrefab; // 이름을 _finalPrefab으로 통일하여 에러 방지 private float _buildTime; private float _currentProgress = 0f; - private Vector2Int _size; // 사이즈를 저장할 변수 추가 + private Vector2Int _size; - public void Initialize(GameObject finalPrefab, float time, Vector2Int size) // 매개변수 추가) + public void Initialize(GameObject finalPrefab, float time, Vector2Int size) { - _finalTurretPrefab = finalPrefab; + _finalPrefab = finalPrefab; _buildTime = time; - _size = size; // 사이즈 저장 + _size = size; // UI 생성 및 초기화 if (uiPrefab != null) @@ -26,7 +26,6 @@ public class ConstructionSite : MonoBehaviour _progressSlider = uiObj.GetComponentInChildren(); if (_progressSlider != null) { - _progressSlider.transform.localScale = Vector3.one; // 슬라이더 크기 조절 _progressSlider.maxValue = 1f; _progressSlider.value = 0f; } @@ -36,7 +35,7 @@ public class ConstructionSite : MonoBehaviour public void AdvanceConstruction(float amount) { _currentProgress += amount; - float ratio = _currentProgress / _buildTime; + float ratio = Mathf.Clamp01(_currentProgress / _buildTime); // 슬라이더 업데이트 if (_progressSlider != null) @@ -52,24 +51,46 @@ public class ConstructionSite : MonoBehaviour private void CompleteBuild() { + // 1. 실제 타워 생성 GameObject finalTurret = Instantiate(_finalPrefab, transform.position, Quaternion.identity); - BuildManager.Instance.AlignToGround(finalTurret, 0f); - // [추가] 새로 생긴 터널의 노드들에게 주변 연결을 찾으라고 명령 - TunnelNode[] newNodes = finalTurret.GetComponentsInChildren(); - foreach (var node in newNodes) + // 2. BuildManager를 통한 지면 정렬 (스케일 반영을 위해 호출) + if (BuildManager.Instance != null) { - node.FindNeighborNode(); + BuildManager.Instance.AlignToGround(finalTurret, 0f); } - // [추가] 주변에 있던 기존 노드들도 새 노드를 찾도록 주변 검색 실행 - Collider[] neighbors = Physics.OverlapSphere(transform.position, 5f, LayerMask.GetMask("Tunnel")); - foreach (var col in neighbors) - { - TunnelNode neighborNode = col.GetComponent(); - if (neighborNode != null) neighborNode.FindNeighborNode(); - } + // 3. 터널 노드 연결 갱신 (터널인 경우에만 작동) + UpdateTunnelConnections(finalTurret); + // 4. 토대 제거 Destroy(gameObject); } + + private void UpdateTunnelConnections(GameObject newTurret) + { + // 3-1. 새로 생성된 타워 내부의 모든 TunnelNode를 찾아 주변 탐색 실행 + TunnelNode[] newNodes = newTurret.GetComponentsInChildren(); + if (newNodes.Length > 0) + { + foreach (var node in newNodes) + { + node.FindNeighborNode(); + } + + // 3-2. 주변에 이미 설치된 다른 터널 노드들도 새로운 터널을 인식하도록 재탐색 명령 + // 5f는 격자 크기에 맞춰 적절히 조절 (일반적으로 격자 한 칸 이상이면 충분) + Collider[] neighbors = Physics.OverlapSphere(transform.position, 5f, LayerMask.GetMask("Tunnel")); + foreach (var col in neighbors) + { + TunnelNode neighborNode = col.GetComponentInParent(); + if (neighborNode != null && !System.Array.Exists(newNodes, x => x == neighborNode)) + { + neighborNode.FindNeighborNode(); + } + } + + Debug.Log($"[Construction] {newTurret.name} 터널 연결 갱신 완료"); + } + } } \ No newline at end of file