星星博客 »  > 

【U3D】UGUI拖拽

一、画布overlay模式

public class EventDemo : MonoBehaviour, IPointerClickHandler, IDragHandler,IBeginDragHandler
{
    private Vector2 diffVector;
    public void OnBeginDrag(PointerEventData eventData)
    {
        Vector2 objVector = this.transform.position;
        diffVector = objVector - eventData.position;
    }

    public void OnDrag(PointerEventData eventData)
    {
        //UI随鼠标点击位置移动
        this.transform.position = eventData.position + diffVector;
		//UI中心随鼠标移动,无需OnBeginDrag
		//this.transform.position = eventData.position;
    }
}

二、画布camera模式

public class EventDemo : MonoBehaviour, IPointerClickHandler, IDragHandler,IBeginDragHandler
{
    private Vector3 diffVector;
    private Vector3 worldPos;
    public void OnBeginDrag(PointerEventData eventData)
    {
        RectTransform parentRTF = this.transform.parent as RectTransform;
        RectTransformUtility.ScreenPointToWorldPointInRectangle(parentRTF, eventData.position, eventData.pressEventCamera, out worldPos);
        diffVector = this.transform.position - worldPos;
    }

    public void OnDrag(PointerEventData eventData)
    {
        //UI随鼠标点击位置移动
        RectTransform parentRTF = this.transform.parent as RectTransform;//将屏幕坐标转换为物体的世界坐标
        RectTransformUtility.ScreenPointToWorldPointInRectangle(parentRTF, eventData.position, eventData.pressEventCamera, out worldPos);
        this.transform.position = worldPos+diffVector;
        
		//UI中心随鼠标移动,无需OnBeginDrag
		//RectTransform parentRTF = this.transform.parent as RectTransform;
        //RectTransformUtility.ScreenPointToWorldPointInRectangle(parentRTF, eventData.position, eventData.pressEventCamera, out worldPos);
        //this.transform.position = worldPos;
    }
}

相关文章