首页 > 编程语言 > Unity UI实现拖拽旋转
2021
08-10

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);

    }

效果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧