unity EventSystems事件系统实现UI拖拽移动,缩放大小

仅用于记录,需要使用事件的类需要继承自对应的接口,并且在类中实现接口对应的方法。图片便于阅读,代码便于复制。

移动思路:通过鼠标按下、拖拽事件来记录初始值和偏移值,并通过偏移值操作UI实现移动。

缩放思路:通过滚轮滚动事件实现。

UI判断:在鼠标按下时判断是否在Map上,拖拽事件中判断bool变量。

public partial class UIPanel : IPointerDownHandler, IDragHandler, IScrollHandler
{
    // 记录初始的偏移量
    private Vector3 positionOffset;

    // 鼠标按下时更新初始偏移量
    public void OnPointerDown(PointerEventData eventData)
    {
       positionOffset = Input.mousePosition - UI_MapScale.localPosition;
    }
    
    // 鼠标拖拽时根据偏移量更新坐标
    public void OnDrag(PointerEventData eventData)
    {
       UI_MapScale.localPosition = Input.mousePosition - positionOffset;
    }

    // 鼠标滚轮滑动时更新UI大小
    public void OnScroll(PointerEventData eventData)
    {
       // 滚轮数值大于0说明是向上滑动, 对应放大UI
       if (Input.GetAxis("Mouse ScrollWheel")>0)
       {
          UI_MapScale.localScale = UI_MapScale.localScale * 1.1f;
       }
       else
       {
          UI_MapScale.localScale = UI_MapScale.localScale / 1.1f;
       }
    }
}
// 注意3个参数的重载是正确用法, 返回一个bool值
isStartMap = RectTransformUtility.RectangleContainsScreenPoint(
             UI_Panel_EarthMap.rectTransform, 
             Input.mousePosition, 
             UICamera);
// 在拖拽事件中根据该布尔值进行判断
    if(!isStartMap) return;
// 这样初始点不在MapUI上的所有拖拽都不会影响到Map移动

猜你喜欢

转载自blog.csdn.net/MeTicals/article/details/129729932