You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity移动端多点触控问题:如何让角色移动不受其他触摸干扰?

Unity移动端多点触控移动控制问题解决方案

问题根源

当前代码的核心问题是逐个处理触摸时,只要某根触摸不在移动区域就立即调用StopMoving,导致如果一根手指在移动区(触发移动),另一根手指点击跳跃按钮,处理后者时会直接覆盖移动指令,强制角色停止。同时每次处理触摸都先调用StopMoving再触发移动,逻辑冗余且易冲突。

解决方案

核心思路:全局检查所有触摸的位置,只要存在至少一个触摸在移动控制区域,就保持对应移动状态,完全忽略其他区域的触摸干扰,最后统一执行移动指令。

修改后的代码

private float screenWidth;
private float screenHeight;

private void Start()
{
    screenWidth = Screen.width;
    screenHeight = Screen.height;
}

private void Update()
{
    bool hasLeftMoveTouch = false;
    bool hasRightMoveTouch = false;

    // 遍历所有触摸,标记有效移动触摸
    for (int i = 0; i < Input.touchCount; i++)
    {
        Touch touch = Input.GetTouch(i);
        // 只处理触摸的有效状态(开始、持续触摸、静止)
        if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
        {
            float touchX = touch.position.x;
            float touchY = touch.position.y;

            // 检测左移区域触摸
            if (touchX < screenWidth / 6 && touchY < screenHeight / 2)
            {
                hasLeftMoveTouch = true;
                // 若需要左移优先级更高,可在此设置 hasRightMoveTouch = false;
            }
            // 检测右移区域触摸
            else if (touchX > screenWidth / 6 && touchX < screenWidth / 2 && touchY < screenHeight / 2)
            {
                hasRightMoveTouch = true;
                // 若需要右移优先级更高,可在此设置 hasLeftMoveTouch = false;
            }
            // 其他区域触摸不影响移动状态
        }
    }

    // 根据全局标记执行最终移动指令
    if (hasLeftMoveTouch)
    {
        PlayerController.MoveLeft();
    }
    else if (hasRightMoveTouch)
    {
        PlayerController.MoveRight();
    }
    else
    {
        // 无任何移动触摸时才停止
        PlayerController.StopMoving();
    }
}

关键改进点

  1. 全局状态记录:用两个布尔变量统一记录是否存在左/右移动触摸,避免逐个触摸指令覆盖。
  2. 过滤触摸状态:只处理有效触摸阶段,避免触摸抬起时的误判。
  3. 忽略非移动触摸:跳跃按钮等其他区域的触摸完全不影响移动状态,只要有一根手指在移动区就保持移动。
  4. 可调整优先级:如果存在同时触摸左右移动区的情况,可通过注释代码设置优先级。

额外优化建议

由于你的移动区域是UI区域,建议改用Unity的EventSystem处理UI触摸:给移动区域UI添加EventTrigger,监听PointerDown、PointerUp、PointerExit事件来触发移动/停止。这种方式能自动拦截UI触摸,避免屏幕坐标检测的误差,多点触控逻辑会更稳定。

内容的提问来源于stack exchange,提问作者Raigan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:41:03