96 lines
3.1 KiB
C#
96 lines
3.1 KiB
C#
using UnityEngine;
|
|
|
|
public class GridSpawner : MonoBehaviour
|
|
{
|
|
public GameObject cellPrefab;
|
|
public int rows = 6;
|
|
public int columns = 5;
|
|
|
|
public GridColor[,] gridCells;
|
|
|
|
// 用於由螢幕座標直接算出格子
|
|
private RectTransform container;
|
|
private Camera canvasCamera;
|
|
private Vector2 origin; // 格子 (0,0) 左下角,在 container 本地座標
|
|
private float cellSize;
|
|
private float step; // 格子大小 + 間距
|
|
|
|
void Start()
|
|
{
|
|
float baseWidth = 1080f;
|
|
float cellBase = 180f;
|
|
float spaceBase = 20f;
|
|
float heightBase = 90f;
|
|
|
|
float scale = Screen.width / baseWidth;
|
|
|
|
cellSize = cellBase * scale;
|
|
float spacing = spaceBase * scale;
|
|
float heightOffset = heightBase * scale;
|
|
|
|
gridCells = new GridColor[columns, rows];
|
|
|
|
RectTransform rt = GetComponent<RectTransform>();
|
|
if (rt == null) rt = gameObject.AddComponent<RectTransform>();
|
|
container = rt;
|
|
step = cellSize + spacing;
|
|
|
|
Canvas canvas = GetComponentInParent<Canvas>();
|
|
if (canvas != null && canvas.rootCanvas.renderMode != RenderMode.ScreenSpaceOverlay)
|
|
canvasCamera = canvas.rootCanvas.worldCamera;
|
|
|
|
rt.anchorMin = new Vector2(0.5f, 0f);
|
|
rt.anchorMax = new Vector2(0.5f, 0f);
|
|
rt.pivot = new Vector2(0.5f, 0f);
|
|
|
|
float totalWidth = columns * cellSize + (columns - 1) * spacing;
|
|
float startX = -totalWidth / 2f;
|
|
float startY = heightOffset;
|
|
|
|
for (int i = 0; i < rows * columns; i++)
|
|
{
|
|
GameObject cellObj = Instantiate(cellPrefab, transform);
|
|
|
|
int x = i % columns;
|
|
int y = i / columns;
|
|
|
|
RectTransform cellRT = cellObj.GetComponent<RectTransform>();
|
|
cellRT.anchorMin = new Vector2(0f, 0f);
|
|
cellRT.anchorMax = new Vector2(0f, 0f);
|
|
cellRT.pivot = new Vector2(0f, 0f);
|
|
cellRT.sizeDelta = new Vector2(cellSize, cellSize);
|
|
|
|
float posX = startX + x * (cellSize + spacing);
|
|
float posY = startY + y * (cellSize + spacing);
|
|
cellRT.anchoredPosition = new Vector2(posX, posY);
|
|
|
|
GridColor cellColor = cellObj.GetComponent<GridColor>();
|
|
cellColor.cellX = x;
|
|
cellColor.cellY = y;
|
|
|
|
gridCells[x, y] = cellColor;
|
|
}
|
|
|
|
origin = gridCells[0, 0].transform.localPosition;
|
|
}
|
|
|
|
// 螢幕座標 → 格子座標;在格子外(含間距)回傳 false,x/y = -1
|
|
public bool CellAt(Vector2 screenPos, out int x, out int y)
|
|
{
|
|
x = y = -1;
|
|
if (gridCells == null) return false;
|
|
if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(container, screenPos, canvasCamera, out Vector2 local))
|
|
return false;
|
|
|
|
Vector2 p = local - origin;
|
|
int cx = Mathf.FloorToInt(p.x / step);
|
|
int cy = Mathf.FloorToInt(p.y / step);
|
|
if (cx < 0 || cy < 0 || cx >= columns || cy >= rows) return false;
|
|
if (p.x - cx * step > cellSize || p.y - cy * step > cellSize) return false;
|
|
|
|
x = cx;
|
|
y = cy;
|
|
return true;
|
|
}
|
|
}
|