手机版 欢迎访问it开发者社区(www.mfbz.cn)网站

当前位置: > 开发

【U3D】UGUI拖拽

时间:2021/5/28 4:51:55|来源:|点击: 次

一、画布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;
    }
}
上一篇:用 Monte Carlo算pi 下一篇:Dockerfile指令

Copyright © 2002-2019 某某自媒体运营 版权所有