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

如何同时控制Unity移动端游戏的玩家移动与相机视角?

多触控操作识别问题修复方案

你的核心问题是依赖触控的索引(GetTouch(0)/GetTouch(1))区分操作,而非唯一的fingerId,再加上lastItem的标记逻辑没和触控生命周期绑定,导致操作顺序混乱。下面是修复思路和代码:

关键调整点

  • 用Dictionary<int, string>存储每个触控ID对应的操作类型("movement"或"camera"),确保每个触控的操作类型不会因新增/移除触控混乱
  • 在触控开始阶段(TouchPhase.Began)判断该触控是否触发摇杆,绑定对应操作类型
  • 遍历所有触控时,根据各自的操作类型分别处理移动或相机旋转

修复后的代码

// 新增字典存储触控ID与操作类型的映射
private Dictionary<int, string> touchOperationMap = new Dictionary<int, string>();

private void Update()
{
    horizontal = joystick.Horizontal();
    vertical = joystick.Vertical();
    Debug.Log("Horizontal: " + horizontal + " Vertical: " + vertical);

    // 处理触控的生命周期:开始、移动、结束
    foreach (Touch touch in Input.touches)
    {
        int id = touch.fingerId;
        
        // 跳过UI上的触控
        if (EventSystem.current.IsPointerOverGameObject(id))
        {
            if (touchOperationMap.ContainsKey(id))
                touchOperationMap.Remove(id);
            continue;
        }

        switch (touch.phase)
        {
            case TouchPhase.Began:
                // 判断该触控是否触发了摇杆(这里用摇杆输入值判断,更准确的话可检测触控位置是否在摇杆UI区域)
                bool isJoystickTouch = (horizontal != 0 || vertical != 0);
                touchOperationMap[id] = isJoystickTouch ? "movement" : "camera";
                break;
            
            case TouchPhase.Moved:
                // 根据触控对应的操作类型处理输入
                if (touchOperationMap.TryGetValue(id, out string operation))
                {
                    if (operation == "camera")
                    {
                        mouseHorizontal = touch.deltaPosition.x * 0.08f;
                        mouseVertical = touch.deltaPosition.y * 0.08f;
                    }
                    // 移动操作由摇杆本身处理,无需额外操作
                }
                break;
            
            case TouchPhase.Ended:
            case TouchPhase.Canceled:
                // 移除结束的触控映射
                if (touchOperationMap.ContainsKey(id))
                    touchOperationMap.Remove(id);
                // 无剩余触控时重置相机输入
                if (touchOperationMap.Count == 0)
                {
                    mouseHorizontal = 0;
                    mouseVertical = 0;
                }
                break;
        }
    }

    Debug.Log("Camera= " + "Horizontal: " + mouseHorizontal + " Vertical: " + mouseVertical);
}

额外优化建议

  • 用horizontal !=0 || vertical !=0判断摇杆触控不够精准,建议直接检测触控position是否在摇杆的RectTransform范围内(用RectTransformUtility.RectangleContainsScreenPoint实现)
  • 若摇杆是Asset Store插件,通常插件会提供是否被触摸的API,直接调用更可靠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:42:33