Unity,UI拖拽(跟随手指移动)
public class UIDrag : MonoBehaviour, IPointerDownHandler, IDragHandler, IEndDragHandler
{#region 字段
public RectTransform canvas;
private RectTransform imgRect;
Vector2 offest = new Vector2();
#endregionprivate void Start()
{
imgRect = this.GetComponent<RectTransform>();
canvas = this.transform.parent.GetComponent<RectTransform>();
}#region 接口
public void OnDrag(PointerEventData eventData)
{
Vector2 mouseDrag = eventData.position;
Vector2 uguiPos = new Vector2();//RectTransformUtility.ScreenPointToLocalPointInRectangle() 把屏幕坐标转换成UI坐标
//canvas 为当前物体的父物体的RectTransform
bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas,mouseDrag,eventData.enterEventCamera,out uguiPos);
if (isRect)
{
imgRect.anchoredPosition = offest + uguiPos;
}
}public void OnEndDrag(PointerEventData eventData)
{
offest = Vector2.zero;
}public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("按下");
Vector2 mouseDown = eventData.position; //鼠标按下时的屏幕坐标
Vector2 mouseUguiPos = new Vector2(); //返回的UGUI坐标
bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas,mouseDown,eventData.enterEventCamera,out mouseUguiPos);
if (isRect)
{
offest = imgRect.anchoredPosition - mouseUguiPos; //计算点击在UI上但是没点击在UI正中心
Debug.Log(offest);
}
}#endregion
}
Unity,UI拖拽(跟随手指移动)
public class UIDrag : MonoBehaviour, IPointerDownHandler, IDragHandler, IEndDragHandler
{#region 字段
public RectTransform canvas;
private RectTransform imgRect;
Vector2 offest = new Vector2();
#endregionprivate void Start()
{
imgRect = this.GetComponent<RectTransform>();
canvas = this.transform.parent.GetComponent<RectTransform>();
}#region 接口
public void OnDrag(PointerEventData eventData)
{
Vector2 mouseDrag = eventData.position;
Vector2 uguiPos = new Vector2();//RectTransformUtility.ScreenPointToLocalPointInRectangle() 把屏幕坐标转换成UI坐标
//canvas 为当前物体的父物体的RectTransform
bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas,mouseDrag,eventData.enterEventCamera,out uguiPos);
if (isRect)
{
imgRect.anchoredPosition = offest + uguiPos;
}
}public void OnEndDrag(PointerEventData eventData)
{
offest = Vector2.zero;
}public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("按下");
Vector2 mouseDown = eventData.position; //鼠标按下时的屏幕坐标
Vector2 mouseUguiPos = new Vector2(); //返回的UGUI坐标
bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas,mouseDown,eventData.enterEventCamera,out mouseUguiPos);
if (isRect)
{
offest = imgRect.anchoredPosition - mouseUguiPos; //计算点击在UI上但是没点击在UI正中心
Debug.Log(offest);
}
}#endregion
}