603 lines
21 KiB
C#
603 lines
21 KiB
C#
using System.Collections.Generic;
|
|
using Unity.Netcode;
|
|
using UnityEngine;
|
|
using UnityEngine.InputSystem;
|
|
using UnityEngine.EventSystems;
|
|
|
|
namespace Northbound
|
|
{
|
|
public class BuildingPlacement : NetworkBehaviour
|
|
{
|
|
[Header("Settings")]
|
|
public LayerMask groundLayer;
|
|
public float maxPlacementDistance = 100f;
|
|
|
|
[Header("Preview Materials")]
|
|
public Material validMaterial;
|
|
public Material invalidMaterial;
|
|
|
|
[Header("Current Selection")]
|
|
public int selectedBuildingIndex = 0;
|
|
|
|
[Header("Debug Visualization")]
|
|
public bool showGridBounds = true;
|
|
|
|
[Header("Drag Building")]
|
|
[Tooltip("드래그 건설 활성화")]
|
|
public bool enableDragBuilding = true;
|
|
[Tooltip("드래그 건설 시 최대 건물 수")]
|
|
public int maxDragBuildingCount = 50;
|
|
|
|
private bool isBuildModeActive = false;
|
|
private GameObject previewObject;
|
|
private int currentRotation = 0; // 0-3
|
|
private Material[] originalMaterials;
|
|
private Renderer[] previewRenderers;
|
|
private PlayerInputActions _inputActions;
|
|
|
|
// 드래그 건설 관련
|
|
private bool isDragging = false;
|
|
private Vector3 dragStartPosition;
|
|
private List<GameObject> dragPreviewObjects = new List<GameObject>();
|
|
private List<Vector3> dragBuildingPositions = new List<Vector3>();
|
|
|
|
public override void OnNetworkSpawn()
|
|
{
|
|
if (!IsOwner) return;
|
|
|
|
_inputActions = new PlayerInputActions();
|
|
_inputActions.Player.ToggleBuildMode.performed += OnToggleBuildMode;
|
|
_inputActions.Player.Rotate.performed += OnRotate;
|
|
_inputActions.Player.Build.performed += OnBuildPressed;
|
|
_inputActions.Player.Build.canceled += OnBuildReleased;
|
|
_inputActions.Player.Cancel.performed += OnCancel;
|
|
_inputActions.Enable();
|
|
|
|
// Create default materials if not assigned
|
|
if (validMaterial == null)
|
|
{
|
|
validMaterial = CreateGhostMaterial(new Color(0, 1, 0, 0.5f));
|
|
}
|
|
|
|
if (invalidMaterial == null)
|
|
{
|
|
invalidMaterial = CreateGhostMaterial(new Color(1, 0, 0, 0.5f));
|
|
}
|
|
}
|
|
|
|
private Material CreateGhostMaterial(Color color)
|
|
{
|
|
// Try to find appropriate shader for current render pipeline
|
|
Shader shader = Shader.Find("Universal Render Pipeline/Lit");
|
|
if (shader == null)
|
|
shader = Shader.Find("Standard");
|
|
if (shader == null)
|
|
shader = Shader.Find("Diffuse");
|
|
|
|
Material mat = new Material(shader);
|
|
|
|
// Set base color
|
|
if (mat.HasProperty("_BaseColor"))
|
|
mat.SetColor("_BaseColor", color); // URP
|
|
else if (mat.HasProperty("_Color"))
|
|
mat.SetColor("_Color", color); // Standard
|
|
|
|
// Enable transparency
|
|
if (mat.HasProperty("_Surface"))
|
|
{
|
|
// URP Transparency
|
|
mat.SetFloat("_Surface", 1); // Transparent
|
|
mat.SetFloat("_Blend", 0); // Alpha
|
|
mat.SetFloat("_AlphaClip", 0);
|
|
mat.SetFloat("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
|
|
mat.SetFloat("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
|
|
mat.SetFloat("_ZWrite", 0);
|
|
mat.renderQueue = 3000;
|
|
mat.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
|
|
mat.EnableKeyword("_ALPHAPREMULTIPLY_ON");
|
|
}
|
|
else
|
|
{
|
|
// Standard RP Transparency
|
|
mat.SetFloat("_Mode", 3); // Transparent mode
|
|
mat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
|
|
mat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
|
|
mat.SetInt("_ZWrite", 0);
|
|
mat.DisableKeyword("_ALPHATEST_ON");
|
|
mat.EnableKeyword("_ALPHABLEND_ON");
|
|
mat.DisableKeyword("_ALPHAPREMULTIPLY_ON");
|
|
mat.renderQueue = 3000;
|
|
}
|
|
|
|
return mat;
|
|
}
|
|
|
|
public override void OnNetworkDespawn()
|
|
{
|
|
if (IsOwner && _inputActions != null)
|
|
{
|
|
_inputActions.Player.ToggleBuildMode.performed -= OnToggleBuildMode;
|
|
_inputActions.Player.Rotate.performed -= OnRotate;
|
|
_inputActions.Player.Build.performed -= OnBuildPressed;
|
|
_inputActions.Player.Build.canceled -= OnBuildReleased;
|
|
_inputActions.Player.Cancel.performed -= OnCancel;
|
|
_inputActions.Disable();
|
|
_inputActions.Dispose();
|
|
}
|
|
|
|
ClearDragPreviews();
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (!IsOwner) return;
|
|
|
|
if (isBuildModeActive)
|
|
{
|
|
if (isDragging && enableDragBuilding)
|
|
{
|
|
UpdateDragPreview();
|
|
}
|
|
else
|
|
{
|
|
UpdatePreviewPosition();
|
|
}
|
|
}
|
|
}
|
|
|
|
private void OnCancel(InputAction.CallbackContext context)
|
|
{
|
|
// 드래그 중일 때만 취소
|
|
if (isDragging && isBuildModeActive)
|
|
{
|
|
CancelDrag();
|
|
Debug.Log("<color=yellow>[BuildingPlacement] 드래그 건설 취소됨</color>");
|
|
}
|
|
}
|
|
|
|
private void OnToggleBuildMode(InputAction.CallbackContext context)
|
|
{
|
|
isBuildModeActive = !isBuildModeActive;
|
|
|
|
if (isBuildModeActive)
|
|
{
|
|
// UI 표시
|
|
if (BuildingQuickslotUI.Instance != null)
|
|
{
|
|
BuildingQuickslotUI.Instance.ShowQuickslot(this);
|
|
}
|
|
|
|
CreatePreview();
|
|
}
|
|
else
|
|
{
|
|
// UI 숨김
|
|
if (BuildingQuickslotUI.Instance != null)
|
|
{
|
|
BuildingQuickslotUI.Instance.HideQuickslot();
|
|
}
|
|
|
|
// 드래그 중이었다면 취소
|
|
if (isDragging)
|
|
{
|
|
CancelDrag();
|
|
Debug.Log("<color=yellow>[BuildingPlacement] 건설 모드 종료로 드래그 취소됨</color>");
|
|
}
|
|
|
|
DestroyPreview();
|
|
ClearDragPreviews();
|
|
}
|
|
|
|
Debug.Log($"[BuildingPlacement] 건설 모드 {(isBuildModeActive ? "활성화" : "비활성화")}");
|
|
}
|
|
|
|
/// <summary>
|
|
/// UI에서 건물 선택 시 호출
|
|
/// </summary>
|
|
public void SetSelectedBuilding(int index)
|
|
{
|
|
if (index < 0 || BuildingManager.Instance == null ||
|
|
index >= BuildingManager.Instance.availableBuildings.Count)
|
|
{
|
|
Debug.LogWarning($"[BuildingPlacement] 유효하지 않은 건물 인덱스: {index}");
|
|
return;
|
|
}
|
|
|
|
selectedBuildingIndex = index;
|
|
currentRotation = 0; // 회전 초기화
|
|
|
|
// 드래그 중이었다면 취소
|
|
if (isDragging)
|
|
{
|
|
CancelDrag();
|
|
Debug.Log("<color=yellow>[BuildingPlacement] 건물 변경으로 드래그 취소됨</color>");
|
|
}
|
|
|
|
// 프리뷰 다시 생성
|
|
if (isBuildModeActive)
|
|
{
|
|
DestroyPreview();
|
|
CreatePreview();
|
|
}
|
|
|
|
Debug.Log($"[BuildingPlacement] 건물 선택됨: {BuildingManager.Instance.availableBuildings[index].buildingName}");
|
|
}
|
|
|
|
private void CreatePreview()
|
|
{
|
|
if (!ValidateBuildingData(selectedBuildingIndex, out BuildingData data))
|
|
{
|
|
return;
|
|
}
|
|
|
|
previewObject = Instantiate(data.prefab);
|
|
SetupPreviewObject(previewObject, validMaterial);
|
|
Debug.Log($"[BuildingPlacement] 프리뷰 생성됨: {data.buildingName}");
|
|
}
|
|
|
|
private bool ValidateBuildingData(int index, out BuildingData data)
|
|
{
|
|
data = null;
|
|
|
|
if (BuildingManager.Instance == null)
|
|
{
|
|
Debug.LogWarning("[BuildingPlacement] BuildingManager가 없습니다.");
|
|
return false;
|
|
}
|
|
|
|
if (index < 0 || index >= BuildingManager.Instance.availableBuildings.Count)
|
|
{
|
|
Debug.LogWarning($"[BuildingPlacement] 유효하지 않은 건물 인덱스: {index}");
|
|
return false;
|
|
}
|
|
|
|
data = BuildingManager.Instance.availableBuildings[index];
|
|
if (data == null || data.prefab == null)
|
|
{
|
|
Debug.LogWarning("[BuildingPlacement] BuildingData 또는 Prefab이 없습니다.");
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
private void SetupPreviewObject(GameObject previewObj, Material material)
|
|
{
|
|
NetworkObject netObj = previewObj.GetComponent<NetworkObject>();
|
|
if (netObj != null)
|
|
{
|
|
Destroy(netObj);
|
|
}
|
|
|
|
Building building = previewObj.GetComponent<Building>();
|
|
if (building != null)
|
|
{
|
|
Destroy(building);
|
|
}
|
|
|
|
Renderer[] renderers = previewObj.GetComponentsInChildren<Renderer>();
|
|
foreach (var renderer in renderers)
|
|
{
|
|
Material[] mats = new Material[renderer.materials.Length];
|
|
for (int i = 0; i < mats.Length; i++)
|
|
{
|
|
mats[i] = material;
|
|
}
|
|
renderer.materials = mats;
|
|
}
|
|
|
|
foreach (var collider in previewObj.GetComponentsInChildren<Collider>())
|
|
{
|
|
collider.enabled = false;
|
|
}
|
|
}
|
|
|
|
private void DestroyPreview()
|
|
{
|
|
if (previewObject != null)
|
|
{
|
|
Destroy(previewObject);
|
|
previewObject = null;
|
|
}
|
|
}
|
|
|
|
private void UpdatePreviewPosition()
|
|
{
|
|
if (previewObject == null || BuildingManager.Instance == null)
|
|
return;
|
|
|
|
Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
|
|
|
|
if (Physics.Raycast(ray, out RaycastHit hit, maxPlacementDistance, groundLayer))
|
|
{
|
|
BuildingData data = BuildingManager.Instance.availableBuildings[selectedBuildingIndex];
|
|
|
|
bool isValid = BuildingManager.Instance.IsValidPlacement(data, hit.point, currentRotation, out Vector3 snappedPosition);
|
|
|
|
previewObject.transform.position = snappedPosition + data.placementOffset;
|
|
previewObject.transform.rotation = Quaternion.Euler(0, currentRotation * 90f, 0);
|
|
|
|
Material targetMat = isValid ? validMaterial : invalidMaterial;
|
|
UpdatePreviewMaterials(previewRenderers, targetMat);
|
|
}
|
|
}
|
|
|
|
private void UpdatePreviewMaterials(Renderer[] renderers, Material material)
|
|
{
|
|
if (renderers == null) return;
|
|
|
|
foreach (var renderer in renderers)
|
|
{
|
|
Material[] mats = new Material[renderer.materials.Length];
|
|
for (int i = 0; i < mats.Length; i++)
|
|
{
|
|
mats[i] = material;
|
|
}
|
|
renderer.materials = mats;
|
|
}
|
|
}
|
|
|
|
private void OnRotate(InputAction.CallbackContext context)
|
|
{
|
|
if (!isBuildModeActive) return;
|
|
|
|
// 드래그 중에는 회전 불가
|
|
if (isDragging)
|
|
{
|
|
Debug.Log("<color=yellow>[BuildingPlacement] 드래그 중에는 회전할 수 없습니다</color>");
|
|
return;
|
|
}
|
|
|
|
currentRotation = (currentRotation + 1) % 4;
|
|
}
|
|
|
|
private void OnBuildPressed(InputAction.CallbackContext context)
|
|
{
|
|
if (!isBuildModeActive || IsPointerOverUI())
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (enableDragBuilding)
|
|
{
|
|
// 드래그 시작
|
|
Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
|
|
if (Physics.Raycast(ray, out RaycastHit hit, maxPlacementDistance, groundLayer))
|
|
{
|
|
isDragging = true;
|
|
dragStartPosition = hit.point;
|
|
|
|
// 메인 프리뷰 숨기기
|
|
if (previewObject != null)
|
|
{
|
|
previewObject.SetActive(false);
|
|
}
|
|
|
|
Debug.Log("<color=cyan>[BuildingPlacement] 드래그 건설 시작 (ESC로 취소 가능)</color>");
|
|
}
|
|
}
|
|
}
|
|
|
|
private void OnBuildReleased(InputAction.CallbackContext context)
|
|
{
|
|
if (!isBuildModeActive) return;
|
|
|
|
if (enableDragBuilding && isDragging)
|
|
{
|
|
// 드래그 종료 - 배치 실행
|
|
ExecuteDragBuild();
|
|
isDragging = false;
|
|
|
|
// 메인 프리뷰 다시 표시
|
|
if (previewObject != null)
|
|
{
|
|
previewObject.SetActive(true);
|
|
}
|
|
|
|
ClearDragPreviews();
|
|
}
|
|
else if (!enableDragBuilding)
|
|
{
|
|
// 단일 건물 배치 (드래그 비활성화 시)
|
|
OnBuild();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 드래그 취소
|
|
/// </summary>
|
|
private void CancelDrag()
|
|
{
|
|
if (!isDragging) return;
|
|
|
|
isDragging = false;
|
|
|
|
// 메인 프리뷰 다시 표시
|
|
if (previewObject != null)
|
|
{
|
|
previewObject.SetActive(true);
|
|
}
|
|
|
|
// 드래그 프리뷰 정리
|
|
ClearDragPreviews();
|
|
}
|
|
|
|
private void UpdateDragPreview()
|
|
{
|
|
if (BuildingManager.Instance == null) return;
|
|
|
|
Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
|
|
if (!Physics.Raycast(ray, out RaycastHit hit, maxPlacementDistance, groundLayer))
|
|
{
|
|
return;
|
|
}
|
|
|
|
BuildingData data = BuildingManager.Instance.availableBuildings[selectedBuildingIndex];
|
|
|
|
Vector3 dragEndPosition = hit.point;
|
|
List<Vector3> positions = CalculateDragBuildingPositions(dragStartPosition, dragEndPosition, data);
|
|
|
|
ClearDragPreviews();
|
|
dragBuildingPositions.Clear();
|
|
|
|
foreach (var pos in positions)
|
|
{
|
|
if (dragPreviewObjects.Count >= maxDragBuildingCount)
|
|
{
|
|
Debug.LogWarning($"[BuildingPlacement] 드래그 건설 최대 개수 도달: {maxDragBuildingCount}");
|
|
break;
|
|
}
|
|
|
|
bool isValid = BuildingManager.Instance.IsValidPlacement(data, pos, currentRotation, out Vector3 snappedPosition);
|
|
|
|
GameObject preview = Instantiate(data.prefab);
|
|
Material targetMat = isValid ? validMaterial : invalidMaterial;
|
|
SetupPreviewObject(preview, targetMat);
|
|
|
|
preview.transform.position = snappedPosition + data.placementOffset;
|
|
preview.transform.rotation = Quaternion.Euler(0, currentRotation * 90f, 0);
|
|
|
|
dragPreviewObjects.Add(preview);
|
|
|
|
if (isValid)
|
|
{
|
|
dragBuildingPositions.Add(snappedPosition);
|
|
}
|
|
}
|
|
}
|
|
|
|
private List<Vector3> CalculateDragBuildingPositions(Vector3 start, Vector3 end, BuildingData data)
|
|
{
|
|
List<Vector3> positions = new List<Vector3>();
|
|
|
|
// 그리드에 스냅
|
|
Vector3 snappedStart = BuildingManager.Instance.SnapToGrid(start);
|
|
Vector3 snappedEnd = BuildingManager.Instance.SnapToGrid(end);
|
|
|
|
// 건물 크기 고려
|
|
Vector3 size = data.GetSize(currentRotation);
|
|
float gridSize = BuildingManager.Instance.gridSize;
|
|
float stepX = Mathf.Max(size.x, gridSize);
|
|
float stepZ = Mathf.Max(size.z, gridSize);
|
|
|
|
// 드래그 방향 계산
|
|
Vector3 direction = snappedEnd - snappedStart;
|
|
float distanceX = Mathf.Abs(direction.x);
|
|
float distanceZ = Mathf.Abs(direction.z);
|
|
|
|
int countX = Mathf.Max(1, Mathf.RoundToInt(distanceX / stepX) + 1);
|
|
int countZ = Mathf.Max(1, Mathf.RoundToInt(distanceZ / stepZ) + 1);
|
|
|
|
float dirX = direction.x >= 0 ? 1 : -1;
|
|
float dirZ = direction.z >= 0 ? 1 : -1;
|
|
|
|
// 그리드 패턴으로 위치 생성
|
|
for (int x = 0; x < countX; x++)
|
|
{
|
|
for (int z = 0; z < countZ; z++)
|
|
{
|
|
Vector3 pos = snappedStart + new Vector3(
|
|
x * stepX * dirX,
|
|
0,
|
|
z * stepZ * dirZ
|
|
);
|
|
positions.Add(pos);
|
|
}
|
|
}
|
|
|
|
return positions;
|
|
}
|
|
|
|
private void ExecuteDragBuild()
|
|
{
|
|
if (dragBuildingPositions.Count == 0)
|
|
{
|
|
Debug.Log("<color=yellow>[BuildingPlacement] 배치 가능한 건물이 없습니다.</color>");
|
|
return;
|
|
}
|
|
|
|
BuildingData selectedData = BuildingManager.Instance.availableBuildings[selectedBuildingIndex];
|
|
|
|
int successCount = 0;
|
|
foreach (var position in dragBuildingPositions)
|
|
{
|
|
BuildingManager.Instance.RequestPlaceFoundation(selectedBuildingIndex, position, currentRotation);
|
|
successCount++;
|
|
}
|
|
|
|
Debug.Log($"<color=cyan>[BuildingPlacement] 드래그 건설 완료: {successCount}개의 {selectedData.buildingName} 배치 시도</color>");
|
|
}
|
|
|
|
private void ClearDragPreviews()
|
|
{
|
|
foreach (var preview in dragPreviewObjects)
|
|
{
|
|
if (preview != null)
|
|
{
|
|
Destroy(preview);
|
|
}
|
|
}
|
|
dragPreviewObjects.Clear();
|
|
dragBuildingPositions.Clear();
|
|
}
|
|
|
|
private void OnBuild()
|
|
{
|
|
if (!isBuildModeActive || previewObject == null) return;
|
|
|
|
// UI 위에서 클릭한 경우 무시
|
|
if (IsPointerOverUI())
|
|
{
|
|
Debug.Log("<color=cyan>[BuildingPlacement] UI 위에서 클릭함 - 건설 취소</color>");
|
|
return;
|
|
}
|
|
|
|
// Get placement position
|
|
Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
|
|
if (Physics.Raycast(ray, out RaycastHit hit, maxPlacementDistance, groundLayer))
|
|
{
|
|
BuildingData selectedData = BuildingManager.Instance.availableBuildings[selectedBuildingIndex];
|
|
|
|
if (BuildingManager.Instance.IsValidPlacement(selectedData, hit.point, currentRotation, out Vector3 groundPosition))
|
|
{
|
|
// 토대 배치 요청
|
|
BuildingManager.Instance.RequestPlaceFoundation(selectedBuildingIndex, groundPosition, currentRotation);
|
|
Debug.Log($"<color=cyan>[BuildingPlacement] 건설 시작: {selectedData.buildingName}</color>");
|
|
}
|
|
else
|
|
{
|
|
Debug.Log("<color=yellow>[BuildingPlacement] 배치할 수 없는 위치입니다.</color>");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 마우스 포인터가 UI 위에 있는지 확인
|
|
/// </summary>
|
|
private bool IsPointerOverUI()
|
|
{
|
|
// EventSystem이 없으면 UI 체크 불가능
|
|
if (EventSystem.current == null)
|
|
return false;
|
|
|
|
// New Input System을 사용하는 경우
|
|
if (Mouse.current != null)
|
|
{
|
|
Vector2 mousePosition = Mouse.current.position.ReadValue();
|
|
return EventSystem.current.IsPointerOverGameObject();
|
|
}
|
|
|
|
// Legacy Input System (폴백)
|
|
return EventSystem.current.IsPointerOverGameObject();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 건설 모드 활성화 상태 확인
|
|
/// </summary>
|
|
public bool IsBuildModeActive()
|
|
{
|
|
return isBuildModeActive;
|
|
}
|
|
}
|
|
}
|