using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem.EnhancedTouch; using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch; using TouchPhase = UnityEngine.InputSystem.TouchPhase; // 一根手指在本幀的狀態 public struct GridTouch { public int fingerId; public Vector2 position; public bool began; // 本幀新按下 public bool ended; // 本幀放開 / 取消 public int x, y; // 所在格子,不在格子上為 -1 public double pressAge; // 按下事件距今幾秒(用來回推精確的按下時間) public bool OnCell => x >= 0; } // 格子的觸控輸入(EnhancedTouch:同一幀內按下又放開的快速點擊也不會漏掉) // - IgnoreCurrentTouches 之前就按著的手指會被忽略(換畫面時) // - 按下時若最上層是面板、按鈕等 UI,這根手指直到放開都不會送到格子(防穿透) // - 編輯器裡用滑鼠模擬觸控 public class GridInput { private readonly Grid grid; private readonly HashSet ignored = new HashSet(); private readonly List touches = new List(); // 按下事件最多回推的秒數(避免掉幀時判定被推太遠) private const double MaxPressAge = 0.1; public GridInput(Grid grid) { this.grid = grid; EnhancedTouchSupport.Enable(); #if UNITY_EDITOR TouchSimulation.Enable(); #endif } public void IgnoreCurrentTouches() { foreach (var t in Touch.activeTouches) ignored.Add(t.touchId); } // blocked = true 時(例如開著對話框)所有新的觸控都不送到格子 public List Poll(bool blocked = false) { touches.Clear(); double now = Time.realtimeSinceStartupAsDouble; foreach (var t in Touch.activeTouches) { int id = t.touchId; TouchPhase phase = t.phase; bool ended = phase == TouchPhase.Ended || phase == TouchPhase.Canceled; bool began = phase == TouchPhase.Began; if (began && (blocked || UIHitTest.IsBlocked(t.screenPosition))) ignored.Add(id); if (ignored.Contains(id)) { if (ended) ignored.Remove(id); continue; } Vector2 pos = t.screenPosition; if (ended) { touches.Add(new GridTouch { fingerId = id, ended = true, x = -1, y = -1, position = pos }); continue; } grid.CellAt(pos, out int x, out int y); double age = began ? System.Math.Min(MaxPressAge, System.Math.Max(0, now - t.startTime)) : 0; touches.Add(new GridTouch { fingerId = id, position = pos, began = began, x = x, y = y, pressAge = age }); } return touches; } // 本幀是否有新的點擊(任意位置,結算畫面「點擊繼續」用) public static bool AnyNewTap() { foreach (var t in Touch.activeTouches) if (t.phase == TouchPhase.Began) return true; return false; } }