Android自制俄罗斯方块触摸输入系统失效问题求助
Android俄罗斯方块触摸交互问题修复方案
针对你遇到的触摸交互异常问题,核心症结在于滑动操作后未标记状态导致松开仍触发旋转,同时滑动逻辑存在重复触发和适配缺陷,以下是修复方案及代码说明:
问题核心
- 滑动后松开仍触发旋转:原代码未标记触摸为滑动操作,
TouchPhase.Ended阶段仍会执行旋转逻辑 - 滑动过程中多次触发移动:每次
TouchPhase.Moved都会检查阈值,可能导致方块连续多次移动 - 固定阈值不适配多分辨率:75px的阈值在小屏手机上判定过严,大屏手机上判定过松
修复后代码
private Vector2 touchStartPos; private bool isSwipeDetected = false; // 标记当前触摸是否为滑动操作 private bool hasTriggeredMove = false; // 避免滑动过程重复触发移动 private float swipeThreshold; // 动态适配屏幕的滑动阈值 private void Awake() { // 用屏幕宽度的5%作为滑动阈值,适配不同分辨率手机 swipeThreshold = Screen.width * 0.05f; } private void Update() { this.board.Clear(this); this.lockTime += Time.deltaTime; if (Input.touchCount > 0) { Touch touch = Input.GetTouch(0); switch (touch.phase) { case TouchPhase.Began: touchStartPos = touch.position; isSwipeDetected = false; hasTriggeredMove = false; break; case TouchPhase.Moved: if (!isSwipeDetected && !hasTriggeredMove) { Vector2 touchDelta = touch.position - touchStartPos; float horizontalDelta = touchDelta.x; float verticalDelta = touchDelta.y; // 优先判断左右滑动 if (Mathf.Abs(horizontalDelta) > Mathf.Abs(verticalDelta)) { if (Mathf.Abs(horizontalDelta) > swipeThreshold) { isSwipeDetected = true; hasTriggeredMove = true; if (horizontalDelta > 0) { Debug.Log("向右移动"); Move(Vector2Int.right); } else { Debug.Log("向左移动"); Move(Vector2Int.left); } } } // 判断向下滑动 else if (verticalDelta < -swipeThreshold) { isSwipeDetected = true; hasTriggeredMove = true; Debug.Log("向下移动"); Move(Vector2Int.down); } } break; case TouchPhase.Ended: // 仅未检测到滑动的触摸,才触发旋转 if (!isSwipeDetected) { Debug.Log("触发旋转"); Rotate(1); } break; } } }
关键修改说明
- 状态标记优化:新增
isSwipeDetected标记滑动操作,确保滑动后松开不触发旋转;hasTriggeredMove避免滑动过程中重复执行移动逻辑 - 动态阈值适配:在
Awake中根据屏幕宽度计算阈值,适配不同尺寸的Android设备 - 逻辑结构梳理:用
switch替代嵌套else if,代码可读性更强 - 变量语义修正:将
isRotating改为isSwipeDetected,避免逻辑混淆
若需要滑动时持续移动方块(如按住滑动连续移动),可移除hasTriggeredMove标记,同时添加移动间隔控制(如通过时间阈值限制每秒移动次数),避免移动过快。
内容的提问来源于stack exchange,提问作者zuzi
相关产品推荐
相关产品推荐

