[unity]如何判斷鼠標/觸摸滑動方向

[unity]如何判斷鼠標/觸摸滑動方向


PC端跟手機端都可以用
效果爲從屏幕上任意位置向其他位置滑動的時候,檢測滑動方向,這裏只寫了上下左右四方向,一般情況下也夠用了


    Vector2 lastPos;//鼠標上次位置
    Vector2 currPos;//鼠標當前位置
    Vector2 offset;//兩次位置的偏移值

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            lastPos = Input.mousePosition;
        }

        if (Input.GetMouseButtonUp(0))
        {
            currPos = Input.mousePosition;
            offset = currPos - lastPos;
            DoMatch(offset);

        }
    }

	void DoMatch(Vector2 _offset)
	{
		//水平移動
        if (Mathf.Abs(offset.x) > Mathf.Abs(offset.y))
        {
        	if (offset.x > 0)
        	{
        		Debug.Log("右");
        	}
        	else
        	{
        		Debug.Log("左");
        	}
        }
        else//垂直移動
        {
            if (offset.y > 0)
            {
            	Debug.Log("上");
            }
            else
            {
            	Debug.Log("下");
            }
         }
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章