IPointerEnterHandler OnPointerEnter 当鼠标进入
IPointerExitHandler OnPointerExit 当鼠标离开
//利用指针进入和退出事件,可以实现toolTip功能
IPointerDownHandler OnPointerDown 当鼠标按下
//在可视元素矩形区域内按下时相应
IPointerUpHandler OnPointerUp 当鼠标抬起
//在可视元素矩形区域内按下后,在任意地方抬起是相应
IPointerClickHandler OnPointerClick 当鼠标点击
//在可视元素矩形区域内按下后,且在同意可视元素矩形区域内抬起是相应
IBeginDragHandler OnBeginDrag 当开始拖拽
IDragHandler OnDrag 当拖拽中
IEndDragHandler OnEndDrag 当结束拖拽
IDropHandler OnDrop 当放下
IScrollHandler OnScroll 当滚动
IUpdateSelectedHandler OnUpdateSelected 当每个选择对象
ISelectHandler OnSelect 当对象变为选定
IDeselectHandler OnDeselect 当对象取消选的
IMoveHandler OnMove 当移动时
ISubmitHandler OnSubmit 当提交按钮被按下
ICancelHandler OnCancel 当取消按钮被按下
public class Item : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, ICanvasRaycastFilter
{
private static Transform TrCanvas;
private Transform TrNowParent;
private bool isRayCastLocationValid = true; // 默认射线不能穿透物品
public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
{ return isRayCastLocationValid; }
public void OnBeginDrag(PointerEventData eventData)
{
if (TrCanvas == null)
{ TrCanvas = GameObject.Find("Canvas").transform; }
// 物品是格子的子物体,NowParent记录的是当前物品属于哪个格子
TrNowParent = transform.parent;
// 指定Canvas为父物体,将当前拖拽的游戏物品置前
transform.SetParent(TrCanvas);
isRayCastLocationValid = false;
}
public void OnDrag(PointerEventData eventData)
{ transform.position = Input.mousePosition; }
public void OnEndDrag(PointerEventData eventData)
{ GameObject go = eventData.pointerCurrentRaycast.gameObject;
if (go)
{
// 当检测到的标签是Cell,证明底下是一个空的格子,那么我们将游戏物品放置到空格子当中
if (go.tag.Equals("Cell"))
{ SetParentAndPosition(transform, go.transform); }
else if (go.tag.Equals("Item"))
{
// 当检测到的是游戏物品的时候,两个游戏物品需要交换位置
SetParentAndPosition(transform, go.transform.parent);
SetParentAndPosition(go.transform, TrNowParent); }
else
{ SetParentAndPosition(transform, TrNowParent); } }
else
{ SetParentAndPosition(transform, TrNowParent);
}
isRayCastLocationValid = true; }
private void SetParentAndPosition(Transform child, Transform parent)
{ child.SetParent(parent); child.position = parent.position; }}