UGUI 自带有拖拽事件,我们具体来实现看看,为了便于理解,我尽量去除不必要的代码.
第一步:继承3个接口:IBeginDragHandler,IDragHandler,IEndDragHandler,分别是拖拽开始,拖拽途中,拖拽结束.(实现相应方法)
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class NeedMountScript : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler{
public void OnBeginDrag(PointerEventData eventData){
Debug.Log("开始拖拽");
}
public void OnDrag(PointerEventData eventData){
Debug.Log(eventData.position);
}
public void OnEndDrag(PointerEventData eventData){
Debug.Log("结束拖拽");
}
}
我们打印出 eventData.position,可以明白这个坐标就是屏幕坐标,左下角起始点(0,0)
第二步:让 ui 跟随鼠标移动.
只需要3句话:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class NeedMountScript : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler{
public void OnBeginDrag(PointerEventData eventData){
Debug.Log("开始拖拽");
}
public void OnDrag(PointerEventData eventData){
Vector3 pos;
RectTransformUtility.ScreenPointToWorldPointInRectangle(GetComponent<Image>().rectTransform,eventData.position,eventData.pressEventCamera,out pos);
transform.position = pos;
}
public void OnEndDrag(PointerEventData eventData){
Debug.Log("结束拖拽");
}
}
拖拽的时候不停更新 eventData.position 的位置,把他转成世界坐标,不停赋值给图片的 position 就行了,看看实际效果吧!
ps:不要忘了把脚本挂在 ui 上面额,既然实现了拖拽,那么下一篇就来实现虚拟摇杆吧.