87 lines
3.0 KiB
C#
87 lines
3.0 KiB
C#
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:同一幀內按下又放開的快速點擊也不會漏掉)
|
|
// - 場景開始前就按著的手指會被忽略
|
|
// - 按下時若最上層是面板等 UI,這根手指直到放開都不會送到格子(防穿透)
|
|
// - 以排列規則直接算出格子座標,不必逐格判斷
|
|
public class GridTouchInput
|
|
{
|
|
private readonly GridSpawner grid;
|
|
private readonly List<Transform> gridRoots = new List<Transform>();
|
|
|
|
private readonly HashSet<int> ignored = new HashSet<int>();
|
|
private readonly List<GridTouch> touches = new List<GridTouch>();
|
|
|
|
// 按下事件最多回推的秒數(避免掉幀時判定被推太遠)
|
|
private const double MaxPressAge = 0.1;
|
|
|
|
public GridTouchInput(GridSpawner grid, params Component[] gridParts)
|
|
{
|
|
EnhancedTouchSupport.Enable();
|
|
this.grid = grid;
|
|
foreach (var part in gridParts)
|
|
if (part != null) gridRoots.Add(part.transform);
|
|
}
|
|
|
|
// 場景開始時呼叫:忽略已經按著的手指
|
|
public void IgnoreCurrentTouches()
|
|
{
|
|
foreach (var t in Touch.activeTouches)
|
|
ignored.Add(t.touchId);
|
|
}
|
|
|
|
public List<GridTouch> Poll()
|
|
{
|
|
touches.Clear();
|
|
if (grid == null || grid.gridCells == null) return touches;
|
|
|
|
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 && UIHitTest.IsBlocked(t.screenPosition, gridRoots))
|
|
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;
|
|
}
|
|
}
|