IBeginDragHandler, IDragHandler, IEndDragHandler
1.三个拖拽事件相关接口
* IBeginDragHandler: 开始拖拽事件处理器;开始拖拽的一瞬间触发。
* IDragHandler: 拖拽中事件处理器;拖拽过程中持续触发。
* IEndDragHandler: 结束拖拽事件处理器;拖拽结束的一瞬间触发。
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class ItemDrag : MonoBehaviour ,IBeginDragHandler,IDragHandler,IEndDragHandler
{
private RectTransform m_RT;
void IBeginDragHandler.OnBeginDrag(PointerEventData eventData)
{
print("IBeginDragHandler.OnBeginDrag");
gameObject.GetComponent<Transform>().position = Input.mousePosition;
print("这是实现的拖拽开始接口");
}
void IDragHandler.OnDrag(PointerEventData eventData)
{
print("IDragHandler.OnDrag");
//虽然用Input.mousePosition可以得到一个2D坐标,不过我们现在需要的是3D坐标,看下面
//gameObject.GetComponent<Transform>().position = Input.mousePosition;
//3D坐标获取方法
Vector3 pos;
m_RT = gameObject.GetComponent<RectTransform>();
//屏幕坐标到世界坐标
RectTransformUtility.ScreenPointToWorldPointInRectangle(m_RT,eventData.position,eventData.enterEventCamera,out pos);
m_RT.position = pos;
print("拖拽中……");
}
void IEndDragHandler.OnEndDrag(PointerEventData eventData)
{
print("IEndDragHandler.OnEndDrag");
gameObject.GetComponent<Transform>().position = Input.mousePosition;
print("实现的拖拽结束接口");
}
}
IDragHandler
public void OnDrag(PointerEventData eventData)
{
Vector2 vect = eventData.position - centerPOs;
expectedHandle.position = centerPOs + vect.normalized * distance; //更新位置,中心点加上鼠标向量的归一值乘上距离
angle = Vector2.Angle(Vector2.down, vect); //计算夹角
if (vect.x < 0)
{
angle = 360 - angle;
}
this.transform.localEulerAngles = new Vector3(0, 0, angle);
}
IPointerEnterHandler, IPointerExitHandler
实现监控鼠标的进入和退出UI触发事件
using UnityEngine.EventSystems;
using UnityEngine;
public class UITrigger : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public void OnPointerEnter(PointerEventData eventData)
{
Debug.Log("进入");
}
public void OnPointerExit(PointerEventData eventData)
{
Debug.Log("退出");
}
}
IsPointerOverGameObject
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class MouseExample : MonoBehaviour
{
void Update()
{
// Check if the left mouse button was clicked
if (Input.GetMouseButtonDown(0))
{
// Check if the mouse was clicked over a UI element
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("Clicked on the UI");
}
}
// Check if there is a touch
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
// Check if finger is over a UI element
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
{
Debug.Log("Touched the UI");
}
}
}
}