拖动UI
第一种:
using UnityEngine;
using UnityEngine.EventSystems;
public class test : MonoBehaviour, IDragHandler
{
private RectTransform rt;
// Start is called before the first frame update
void Start()
{
rt = GetComponent<RectTransform>();
}
public void OnDrag(PointerEventData eventData)
{
Vector3 pos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle
(rt, eventData.position, eventData.pressEventCamera,out pos))
{
rt.position = pos;
}
}
」
当鼠标位置需要在ui的左上角时
private Vector3 v3;
void Start()
{
v3 = new Vector3(rt.rect.width / 2, -rt.rect.height / 2);
}
//在ui重新赋值的时候加上v3即可
第二种:
点在哪ui跟随到哪
using UnityEngine;
using UnityEngine.EventSystems;
public class DragUI : MonoBehaviour, IDragHandler, IPointerDownHandler {
private Vector2 offsetPos;
public void OnDrag(PointerEventData eventData)
{
transform.position = eventData.position - offsetPos;
}
public void OnPointerDown(PointerEventData eventData)
{
offsetPos = eventData.position - (Vector2)transform.position;
}
}