using UnityEngine; using UnityEngine.UI; using UnityEngine.InputSystem; public class GridManager : MonoBehaviour { public GameObject cellPrefab; // Grid_cell 預製件 public int rows = 6; public int columns = 5; public GridColor[,] gridCells; public string settingSceneName = "SettingScene"; void Start() { // === 這裡設定比例 === float baseWidth = 1080f; // 你的基準寬度 float cellBase = 180f; // 格子原始比例 float spaceBase = 20f; // 間距原始比例 float heightBase = 90f; // 上推高度 邊60*1.5 // 以螢幕寬度計算等比例縮放 float scale = Screen.width / baseWidth; float cellSize = cellBase * scale; float spacing = spaceBase * scale; float heightOffset = heightBase * scale; // 建立二維陣列 gridCells = new GridColor[columns, rows]; // 計算最底部開始的起點 (Bottom Center) RectTransform rt = GetComponent(); if (rt == null) rt = gameObject.AddComponent(); // 保證錨點是 bottom center rt.anchorMin = new Vector2(0.5f, 0f); rt.anchorMax = new Vector2(0.5f, 0f); rt.pivot = new Vector2(0.5f, 0f); // 整個 grid 的寬度 float totalWidth = columns * cellSize + (columns - 1) * spacing; // 左邊起點(因為錨點是中心) float startX = -totalWidth / 2f; // Y 起點永遠是 0(底部) 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(); // 設定錨點跟 pivot(全用左下) 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 GridColor cellColor = cellObj.GetComponent(); cellColor.cellX = x; cellColor.cellY = y; gridCells[x, y] = cellColor; } } void Update() { DetectTouch(); } void DetectTouch() { if (Touchscreen.current == null) return; foreach (var touch in Touchscreen.current.touches) { if (!touch.isInProgress) continue; Vector2 touchPos = touch.position.ReadValue(); var phase = touch.phase.ReadValue(); // 判定落在哪個格子 for (int y = 0; y < rows; y++) { for (int x = 0; x < columns; x++) { var cell = gridCells[x, y]; if (RectTransformUtility.RectangleContainsScreenPoint( cell.GetComponent(), touchPos)) { if (phase == UnityEngine.InputSystem.TouchPhase.Began) { // 按下瞬間 cell.FlashBlue(); } else { // 持續觸摸 cell.FlashWhite(); } } } } } } }