Unity 限制UI拖拽范围

限制UI拖拽区域

	  /// 
	  /// 移动限制窗口
	  /// 
	  /// 当前需要移动的节点
	  public void RestrictMoveInWindow(RectTransform originTrans)
        {
            Vector3 pos = originTrans.localPosition;
            
            pos.x = Mathf.Clamp(originTrans.localPosition.x, minWidth, maxWidth);
            pos.y = Mathf.Clamp(originTrans.localPosition.y, minHeight, maxHeight);
            
            originTrans.localPosition = pos;
        }

UI拖拽(IBeginDragHandler, IDragHandler, IEndDragHandler)

        public void OnBeginDrag(BaseEventData baseEventData)
        {
            PointerEventData pointerEventData = baseEventData as PointerEventData;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(
                CanvasRectangle, pointerEventData.position, pointerEventData.pressEventCamera, out offset);
            //计算偏移量
            offset = Body.rectTransform.anchoredPosition - offset;
            dragging = true;
        }
        
        public void OnDrag(BaseEventData baseEventData)
        {
            PointerEventData pointerEventData = baseEventData as PointerEventData;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(
                CanvasRectangle, pointerEventData.position, pointerEventData.pressEventCamera, out targetPosition);
            //更新目标位置
            targetPosition = targetPosition + offset;
        }
        
        public void OnEndDrag(BaseEventData baseEventData)
        {
            dragging = false;
        }

        public void Update()
        {
            if (dragging)
            {
                RestrictMoveInWindow(rt);
            }
        }

你可能感兴趣的:(Unity,Skill)