Unity跑酷游戏如何仅接收单指滑动输入,排除多点触控干扰
跑酷游戏单指滑动输入修复方案
问题根因
你当前的代码存在两个核心缺陷:
- 仅在
Input.touchCount == 1时读取滑动偏移,但没有过滤第一根有效触摸的身份,当多指触碰后回到单指状态时,第一根手指的累积位移会被一次性读取,导致方向错乱 - 没有处理触摸结束、取消的边界状态,也没有对滑动偏移做阈值限制,容易触发误操作
修复代码
// 类成员变量,不要放在Update方法内声明 private int _activeFingerId = -1; // 记录当前有效滑动的手指ID,-1表示无有效输入 private const float SwipeThreshold = 0.005f; // 滑动阈值,避免微触碰触发操作 private void Update() { float newz = transform.position.z + movementSpeed * Time.deltaTime; float newx = transform.position.x; float swipeDelta = 0; int touchCount = Input.touchCount; // 超过1根手指,直接清空有效输入,不处理任何滑动 if (touchCount > 1) { _activeFingerId = -1; } // 单指状态下处理输入 else if (touchCount == 1) { Touch currentTouch = Input.GetTouch(0); // 新的触摸开始,记录为有效输入 if (currentTouch.phase == TouchPhase.Began) { _activeFingerId = currentTouch.fingerId; } // 是我们记录的有效手指,且处于滑动状态,计算偏移 else if (currentTouch.fingerId == _activeFingerId && currentTouch.phase == TouchPhase.Moved) { float rawDelta = currentTouch.deltaPosition.x / Screen.width; // 小于阈值的微移动忽略,避免误触 if (Mathf.Abs(rawDelta) > SwipeThreshold) { swipeDelta = rawDelta; } } // 有效手指结束或取消,清空标记 else if (currentTouch.fingerId == _activeFingerId && (currentTouch.phase == TouchPhase.Ended || currentTouch.phase == TouchPhase.Canceled)) { _activeFingerId = -1; } } newx += swipeDelta * 5f * Time.deltaTime; // 可选补充:限制x轴移动范围,避免角色移出屏幕,数值可根据你的场景调整 // newx = Mathf.Clamp(newx, -2f, 2f); transform.position = new Vector3(newx, transform.position.y, newz); }
优化说明
- 用
_activeFingerId跟踪唯一的有效输入手指,只有第一次按下的单指会被响应,直到这根手指松开,中途其他手指的触碰不会干扰输入 - 增加了滑动阈值过滤,微小的触摸抖动不会触发角色移动,提升操作准确性
- 多指触碰时直接清空有效输入标记,避免回到单指时累积位移导致的角色跳变问题
- 可根据你的场景调整
SwipeThreshold和x轴限制范围,匹配操作手感需求
内容的提问来源于stack exchange,提问作者bark
相关产品推荐
相关产品推荐

