Unity 判断 鼠标/触摸 位置是否在指定Ui上,非射线检测方式。触屏移动物体。

版权声明:若侵权请联系删除,转载请备注 https://blog.csdn.net/gheartsea/article/details/85689697

事出有因:
1.项目的触摸点击事件,并且有手指缩放/移动功能。
2.unity本身支持touch功能,这个不多说。
3.当做手指缩放/移动的时候就要判断touch点位置了,但是如果不加任何判断则会乱套。
如:本来想移动A(让A跟随 手指touch 的坐标就行了),但是如果我在B区域触摸并移动手指,A也会跟随移动,这样就不对了。应该是在A所在的区域才有效,才能移动。

解决方法
way1:A物体添加碰撞,鼠标/触摸点的位置发射射线,检测是否碰撞到A上的碰撞体,进而移动。此方法简单,但麻烦。
way2:
首先看一下屏幕坐标的关系:
草图奉上:
屏幕坐标系
1.获取ui的长、宽:m_ui.GetComponent<RectTransform>().rect.width/m_uiGetComponent<RectTransform>().rect.height
2.ui坐标转屏幕坐标:Vector2 pos2D; pos2D = Camera.main.WorldToScreenPoint(m_ui.localPosition);,得到对应的屏幕坐标点。
3.判断 鼠标/触摸 位置是否在ABCD的区域内即可。

上代码

    void Update()
    {
        Debug.Log(IsTouchInUi(Input.mousePosition) ? "在地图上" : "不在上面");//鼠标
        if (Input.touchCount>0)
            Debug.Log(IsTouchInUi(Input.GetTouch(0).deltaPosition) ? "在地图上" : "不在上面");//触屏
        if(Input.GetTouch(0).deltaPosition)
        {
        	//单指触屏移动
        	if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
        	{
        		Vector3 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
        		_map.Translate(touchDeltaPosition.x * 5, -touchDeltaPosition.y * 5, 0);
        	}
        }
    }
    /// <summary>
    /// 获取ui的屏幕坐标
    /// </summary>
    /// <param name="trans">UI物体</param>
    /// <returns></returns>
    Vector3 GetUiToScreenPos(Transform trans)
    {
        _mapWidth = trans.GetComponent<RectTransform>().rect.width;//获取ui的实际宽度
        _mapHight = trans.GetComponent<RectTransform>().rect.height;//长度
        Vector2 pos2D;
        pos2D = Camera.main.WorldToScreenPoint(trans.localPosition);
        Vector3 newPos = new Vector3(pos2D.x, pos2D.y, 0);
        return newPos;
    }
    /// <summary>
    /// 判断是否在ui上
    /// </summary>
    /// <param name="pos">输入的坐标信息</param>
    /// <returns></returns>
    bool IsTouchInUi(Vector3 pos)
    {
        bool isInRect = false;
        Vector3 newPos = GetUiToScreenPos(_map);
        if (Input.mousePosition.x < (newPos.x+_mapWidth/2) && Input.mousePosition.x > (newPos.x-_mapWidth/2) && 
            Input.mousePosition.y < (newPos.y+_mapHight/2) && Input.mousePosition.y > (newPos.y-_mapHight/2))
        {
            isInRect = true;
        }
        return isInRect;
    }

Over

猜你喜欢

转载自blog.csdn.net/gheartsea/article/details/85689697