using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
///<summary>
///鼠标拖拽效果
///</summary>
public class EventDemo : MonoBehaviour,IDragHandler
{
public void OnDrag(PointerEventData eventData)
{
//eventData.position: 光标位置
//this.transform.position = eventData.position; //仅仅适用于Canvas的overLay模式 该模式下屏幕原点与画布原点重合
//通用拖拽
//适用不同的Canvas模式,将屏幕坐标转换为世界坐标
RectTransform Rtf = this.transform.parent as RectTransform; //as关键字强制类型转换
Vector3 WordPos; //世界坐标
//(父物体变换组件,屏幕坐标,摄像机,out 世界坐标)
RectTransformUtility.ScreenPointToWorldPointInRectangle(Rtf, eventData.position, eventData.pressEventCamera, out WordPos);
this.transform.position=WordPos;
}
}
优化:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
///<summary>
///拖拽物体
///</summary>
//思路:对于拖拽物体运动,原理就是物体位置变化到鼠标所在位置 对于Canvas下的overlay模式屏幕坐标和世界坐标重合 只需要this.transform,position=eventData,position
// 对于其他模式下,需要将屏幕坐标转换为世界坐标,再将转换后的世界坐标指定给this.transfrom.position
// 为优化每次拖拽物体无论哪里,都是物体中心点移动到光标位置 将转换后的世界坐标再增加一个偏移量
// 即鼠标点击时,this.transform.position与鼠标点击处的差值 this.transform.position=wordPoint+offset
public class UIDrag : MonoBehaviour, IPointerDownHandler,IDragHandler
{
private Vector3 Offset;
private RectTransform parentRTF;
private void Start()
{
parentRTF = this.transform.parent as RectTransform;
}
//拖拽时调用
public void OnDrag(PointerEventData eventData)
{
Vector3 wordPoint;
//屏幕坐标-->世界坐标
RectTransformUtility.ScreenPointToWorldPointInRectangle(parentRTF, eventData.position, eventData.enterEventCamera, out wordPoint);
//根据偏移量移动当前UI
this.transform.position = wordPoint + Offset;
}
//按下鼠标时调用
public void OnPointerDown(PointerEventData eventData)
{
Vector3 worldPoint;
//屏幕坐标转换为世界坐标
//(屏幕坐标要转化在该平面,要转换的屏幕坐标,摄像机,转换后的世界坐标)
RectTransformUtility.ScreenPointToWorldPointInRectangle(parentRTF, eventData.position, eventData.enterEventCamera, out worldPoint);
Offset = this.transform.position - worldPoint;
}
}
unity中,对于UGUI中事件(Event)的绑定
1.通过编译器的方法,在unity面板中进行绑定
eg:Button中的On click()事件
2.在代码中,对不同UI的事件添加事件监听器AddListener(),如:
public void Fun1()
{
print("Fun1");
}
public void Fun2(string str)
{
print("Fun2" + str);
}
public Button But;
But.Onclick.AddListener(Fun1); //public delegate void UnityAction(); AddListener中参数为一个无参数 无返回值的方法
public InputField IPF;
IPF.OnEndExit.Addlistener(Fun2); //public delegate void UnityAction<T0>(T0 arg0); 参数类型为一个有参数无返回值的方法
3.实现接口
eg:鼠标指针类: 拖拽类 点选类 输入类
IPointerEnterHandler IBeginDragHandler IUpdateSelectedHandler IScrollHandler
IPointerExitHandler IDragHandler ISelectHandler IMoveHandler
IPointDownHandler IEndHandler IDeselectHandler ISubmitHandler
IPointUpHandler IDropHandler ICancelHandler
IPointerClickHandler
实现接口时记得引入命名空间 UnityEngine.EventSystems
eg:注意学习PointEventData类
public class EventDemo : MonoBehaviour,IPointerDownHandler
public void OnPointerDown(PointerEventData eventData)
{
}
4.自定义框架