ProjectDDD/Assets/_Datas/Scripts/CellManager.cs
2025-07-01 12:25:06 +09:00

104 lines
2.8 KiB (Stored with Git LFS)
C#

using System.Diagnostics;
using UnityEngine;
public class CellManager : MonoBehaviour
{
public RectTransform cellCanvas;
public CellUI cell;
public int minX = -20;
public int maxX = 20;
public int minZ = -20;
public int maxZ = 20;
// 0 == 비어있음, 1 == 차있음, 2 == 잠김
public const int offsetZ = 40;
private const int mapSize = 80;
private int[] tiles;
private CellUI[] tileUIs;
void Start()
{
tiles = new int [mapSize * mapSize];
// TODO: 데이터 입력
for (int i = 0; i < mapSize * mapSize; i++)
{
tiles[i] = 0;
}
cell.transform.SetParent(null);
cell.gameObject.SetActive(false);
tileUIs = new CellUI[mapSize * mapSize];
for (int i = 0; i < mapSize * mapSize; i++)
{
var newCell = Instantiate(cell, cellCanvas);
newCell.gameObject.SetActive(true);
tileUIs[i] = newCell.GetComponent<CellUI>();
}
UpdateCells();
}
public static Vector3 CellToWorld(Vector2Int cellPos)
{
var worldX = (cellPos.x - cellPos.y) * 0.5f * 1.414f; // sqrt(2)
var worldZ = -(cellPos.x + cellPos.y) * 0.5f * 1.414f + offsetZ;
return new Vector3(worldX, 0f, worldZ);
}
public static Vector2Int WorldToCell(Vector3 worldPos)
{
var cellX = Mathf.RoundToInt((worldPos.x - (worldPos.z - offsetZ)) / 1.414f);
var cellY = Mathf.RoundToInt((-(worldPos.z - offsetZ) - worldPos.x) / 1.414f);
return new Vector2Int(cellX, cellY);
}
public static int GetCellID(Vector2Int cellPos)
{
return cellPos.x + cellPos.y * mapSize;
}
public static Vector3 GetCellWorldPos(int cellPos)
{
int x = cellPos % mapSize; // x는 열 (가로)
int y = cellPos / mapSize; // y는 행 (세로)
return CellToWorld(new Vector2Int(x, y));
}
private void Update()
{
UpdateCells();
}
public void UpdateCells()
{
for (int i = 0; i < mapSize * mapSize; i++)
{
var worldPos = GetCellWorldPos(i);
// 바운더리체크 함수로 빼기
if (minX > worldPos.x || worldPos.x > maxX)
{
tileUIs[i].gameObject.SetActive(false);
continue;
}
if (minZ > worldPos.z || worldPos.z > maxZ)
{
tileUIs[i].gameObject.SetActive(false);
continue;
}
tileUIs[i].SetTile(tiles[i]);
tileUIs[i].gameObject.SetActive(true);
tileUIs[i].transform.position = GetCellWorldPos(i);
}
}
public void SetupCell(Vector3 position)
{
tiles[GetCellID(WorldToCell(position))] = 1;
}
}