Unity手指滑动多选模型

using UnityEngine;

public class MultiSelect3DTrigger : MonoBehaviour
{
    public Camera rayCamera;

    private Vector3 m_OldInputPos = Vector3.zero;
    private Vector3 m_InputPos = Vector3.zero;

    private int m_OldTouchCount = 0;
    private int m_TouchCount = 0;

    private void Update()
    {
        m_TouchCount = GetTouchCount();
        if (m_TouchCount != m_OldTouchCount)
        {
            m_InputPos = Input.mousePosition;
            if (m_TouchCount == 0)
            {
                //抬起
                OnTouchUp(m_InputPos);
            }
            else
            {
                //按下
                OnTouchDown(m_InputPos);
            }
            m_OldInputPos = m_InputPos;
            m_OldTouchCount = m_TouchCount;
        }
        if (m_TouchCount <= 0)
        {
            return;
        }
        m_InputPos = Input.mousePosition;
        if (m_InputPos != m_OldInputPos)
        {
            m_OldInputPos = m_InputPos;
            //发生移动
            OnTouchMove(m_InputPos);
        }
    }
    //按下
    private void OnTouchDown(Vector3 mousePosition)
    {
        Debug.Log("按下");
        GameObject go = OnRaycast(mousePosition);
        if (go != null)
        {
            Debug.Log($"选中了:{go.name}");
        }
    }
    //抬起
    private void OnTouchUp(Vector3 mousePosition)
    {
        Debug.Log("抬起");
        GameObject go = OnRaycast(mousePosition);
        if (go != null)
        {
            Debug.Log($"选中了:{go.name}");
        }
    }
    //滑动
    private void OnTouchMove(Vector3 mousePosition)
    {
        //选中一串
        Debug.Log("滑动");
        GameObject go = OnRaycast(mousePosition);
        if (go != null)
        {
            Debug.Log($"选中了:{go.name}");
        }
    }

    /// <summary>
    /// 发出射线,并返回射线触碰到的对象,对象上要挂在Collider
    /// </summary>
    /// <param name="mousePosition"></param>
    /// <param name="maxDistance"></param>
    /// <returns></returns>
    private GameObject OnRaycast(Vector3 mousePosition, int maxDistance = 30)
    {
        Ray ray = rayCamera.ScreenPointToRay(mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, maxDistance))
        {
            return hit.collider.gameObject;
        }
        return null;
    }
    /// <summary>
    /// 获取手势按下数量
    /// </summary>
    /// <returns></returns>
    private int GetTouchCount()
    {
#if ((UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR)
        return Input.touchCount;
#else
        if (Input.GetMouseButton(0) || Input.GetMouseButtonUp(0))
        {
            return 1;
        }
        else
        {
            return 0;
        }
#endif
    }


}

演示.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。