使用UI拖动事件(OnDrag)拖拽ui时,位置偏移,效果图:
想要实现效果
方法一:最简单的方法,代码中有相应解释
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
// UGUI拖动图片,脚本挂在Image上即可
public class SyqTest : MonoBehaviour, IPointerDownHandler,IDragHandler
{
Vector3 offPos;//存储按下鼠标时的图片-鼠标位置差
public void OnPointerDown(PointerEventData eventData)
{
offPos = transform.position- Input.mousePosition ;
}
public void OnDrag(PointerEventData eventData)
{
//修改图片为鼠标当前位置并加上位置差
transform.position = offPos + Input.mousePosition;
}
}
方法二:用到了函数ScreenPointToWorldPointInRectangle(),此方法用在OnBeginDrag中有些重复,前者返回的是 在图片范围内的鼠标位置,后者是在图片中单击才会执行。有点类似重复
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
// UGUI拖动图片,脚本挂在Image上即可
public class SyqTest : MonoBehaviour, IDragHandler, IBeginDragHandler
{
Vector3 offPos;//存储按下鼠标时的图片-鼠标位置差
Vector3 arragedPos; //保存经过整理后的向量,用于图片移动
// 开始拖拽
public void OnBeginDrag(PointerEventData eventData)
{
//将屏幕空间上的点转换为位于给定RectTransform平面上的世界空间中的位置
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(transform.GetComponent<RectTransform>(), Input.mousePosition
, eventData.enterEventCamera, out arragedPos))
{
offPos = transform.position - arragedPos;
}
}
// 拖拽中
public void OnDrag(PointerEventData eventData)
{
transform.position = offPos + Input.mousePosition;
}
}
方法三:这个方法较上面两种比较复杂,通过鼠标按下时修改ui的pivont解决。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
// UGUI拖动图片,脚本挂在Image上即可
public class SyqTest : MonoBehaviour, IPointerDownHandler, IDragHandler
{
Vector3 offPos;//存储按下鼠标时的图片-鼠标位置差
Vector3[] corners = new Vector3[4];//存储ui图片四个角世界坐标位置
void Start()
{
//获取ui图片四个角世界坐标位置(顺序:左下,左上,右上,右下)
gameObject.GetComponent<RectTransform>().GetWorldCorners(corners);
}
public void OnPointerDown(PointerEventData eventData)
{
/* 鼠标位置和图片四边角位置都是基于世界坐标的0点开始,
* 我们想要在图像的范围内按照比例计算pivont时, 需要从图片pivont的零点(即:图片左下角位置)开始,
* 所以鼠标点击的坐标和图片右上角的坐标都需要减去图片左下角位置
*/
//鼠标点击坐标 减去左下角坐标
Vector2 mousePos = Input.mousePosition - corners[0];
//图片右上角坐标 减去左下角坐标
Vector2 topRightCorner = corners[2] - corners[0];
/*图片pivont坐标取值范围为(0 ~ 1)
* 处理后的鼠标位置除以图片左上角位置,即可得出要修改图片的pivont点
*/
//获取中心点坐标
Vector2 pivont = new Vector2((mousePos.x / topRightCorner.x), (mousePos.y / topRightCorner.y));
//修改中心点
gameObject.GetComponent<RectTransform>().pivot = pivont;
}
public void OnDrag(PointerEventData eventData)
{
//跟随移动
transform.position = Input.mousePosition;
}
}