Unity3D UGUI窗口拖拽
在开发UGUI时
我们时常需要做一个窗口拖拽的功能
先上代码
using UnityEngine; using UnityEngine.EventSystems; public class DragWindow : MonoBehaviour,IPointerDownHandler,IDragHandler { private Vector2 localMousePos; private Vector3 planeLocalPos; private RectTransform targetObject; private RectTransform parentRectTransform; private RectTransform targetRectTransform; void Awake() { targetObject = this.transform.GetComponent<RectTransform>(); if (targetObject == null) { targetObject = transform as RectTransform; } parentRectTransform = targetObject.parent as RectTransform; targetRectTransform = targetObject as RectTransform; } public void OnPointerDown(PointerEventData data) { planeLocalPos = targetRectTransform.localPosition; RectTransformUtility.ScreenPointToLocalPointInRectangle(parentRectTransform, data.position, data.pressEventCamera, out localMousePos); targetObject.gameObject.transform.SetAsLastSibling(); } public void OnDrag(PointerEventData data) { Vector2 localPointerPosition; if (RectTransformUtility.ScreenPointToLocalPointInRectangle(parentRectTransform, data.position, data.pressEventCamera, out localPointerPosition)) { Vector3 offsetToOriginal = localPointerPosition - localMousePos; targetObject.localPosition = planeLocalPos + offsetToOriginal; } } }
使用方法:
直接将此脚本添加到需要拖拽的窗口就好
此脚本使用了UGUI内置的事件接口IPointerDownHandler和IDragHandler
并在接口方法OnPointerDown和OnDrag实现了相应的拖拽逻辑