Unity UI實現拖拽旋轉

本文實例為大傢分享瞭Unity UI實現拖拽旋轉的具體代碼,供大傢參考,具體內容如下

跟隨鼠標旋轉

第一種效果是跟隨鼠標旋轉,原理是計算下鼠標位置與拖拽物體的相對位移

旋轉方向即可

註意轉換對應空間坐標

新建腳本mono類繼承 IBeginDragHandler, IDragHandler, IEndDragHandler 接口

[SerializeField] private Canvas m_Canvas;
    
    private Vector3? CalculateWorldToScreenPos(Vector3 worldPos)
    {
        if (m_Canvas.renderMode == RenderMode.ScreenSpaceCamera)
        {
            return m_Canvas.worldCamera.WorldToScreenPoint(worldPos);
        }
        else if (m_Canvas.renderMode == RenderMode.ScreenSpaceOverlay)
        {
            Vector3 screenPos = m_Canvas.transform.InverseTransformPoint(worldPos);
            var rectTrans = m_Canvas.transform as RectTransform;
            screenPos.x += rectTrans.rect.width * 0.5f * rectTrans.localScale.x;
            screenPos.y += rectTrans.rect.height * 0.5f * rectTrans.localScale.y;
            return screenPos;
        }

        return null;
    }
    
    public void OnDrag(PointerEventData eventData)
    {
        if (eventData.button != PointerEventData.InputButton.Left) return;
        
        //計算當前物體距離畫佈左下角位置
        Vector3? curScreenPos = CalculateWorldToScreenPos(transform.position);
        if (curScreenPos == null) return;
        //鼠標位置偏移量
        Vector2 offset = eventData.position - (Vector2)curScreenPos.Value;
        if (offset != Vector2.zero)
        {
            transform.rotation = Quaternion.FromToRotation(Vector3.up, offset);
        }
    }

設置下箭頭錨點

效果如下:

手指拖拽旋轉

第二種是根據旋轉速度來旋轉UI 可以實現一些齒輪交互滾動和車把方向盤交互滾動

//旋轉速度
[SerializeField] private float m_RotateSpeed;
    
    public void OnDrag(PointerEventData eventData)
    {
        if (eventData.button != PointerEventData.InputButton.Left) return;

        //手指滑動偏移量
        Vector2 mouseXY = eventData.delta;
        mouseXY *= m_RotateSpeed;

        //計算當前物體距離畫佈左下角位置
        Vector3? curScreenPos = CalculateWorldToScreenPos(transform.position);
        if (curScreenPos == null) return;
        //手指位置偏移量
        Vector2 offset = eventData.position - (Vector2)curScreenPos.Value;

        float value;
        if (Mathf.Abs(mouseXY.x) > Mathf.Abs(mouseXY.y)) // 判斷水平滑動還是垂直滑動
        {
            //手指往水平滑動   下面旋轉跟隨偏移參數  上面與偏移參數相反
            value = mouseXY.x * Mathf.Sign(-offset.y);
        }
        else
        {
            //手指垂直滑動    右邊跟隨偏移參數    左邊與偏移參數相反
            value = mouseXY.y * Mathf.Sign(offset.x);
        }

        transform.Rotate(Vector3.forward, value, Space.Self);

    }

效果如下:

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: