10-01 400 views
UGUI的点击事件本质是发送射线,之前我们使用EasyTouch兼容ugui 响应事件点击出于下面考虑:
1.不用每个响应点击的ui控件上都去挂事件监听脚本, 统一处理
2.丰富的手势不需要再自己去实现, 如单双指滑动swipe, 双指缩放pinch, 双指旋转twist
3.自带摇杆, 改改就能用
EasyTouch 在tick中检测Unity Input的Touch信息, 根据Touch生成Finger, 再根据Finger生成手势Gesture并派发对应事件, 每个Finger调用EventSystem.current.RaycastAll来检查是否点击到ui控件, tick这里需要谨慎处理防止造成性能问题.
EventSystem原理简述:
EventSystem负责总管理, 他收集处理所有的inputModule(默认我们只需要一个StandaloneInputModule即可)并在Tick中Process()当前需要执行的Module来处理Unity Input的Touch信息.
StandaloneInputModule负责总输入控制 (TouchInputModule组件已经废弃), 他在Process时判断执行鼠标或触摸的事件进而调用RaycastAll来处理收集的GraphicRaycaster(OnEnable时注册, OnDisabled移除), 调用其Raycast()方法来处理其所在Canvas响应点击的Graphic组件(移除屏幕视口的不会再处理), 生成Touch的PointerEventData()数据并通过我们熟知的事件派发出去.
运行时, 我们看到的EventSystem组件下会有实时显示, 就走了上面流程.
IPointerEnterHandler – OnPointerEnter – Called when a pointer enters the object
IPointerExitHandler – OnPointerExit – Called when a pointer exits the object
IPointerDownHandler – OnPointerDown – Called when a pointer is pressed on the object
IPointerUpHandler – OnPointerUp – Called when a pointer is released (called on the original the pressed object)
IPointerClickHandler – OnPointerClick – Called when a pointer is pressed and released on the same object
IInitializePotentialDragHandler – OnInitializePotentialDrag – Called when a drag target is found, can be used to initialise values
IBeginDragHandler – OnBeginDrag – Called on the drag object when dragging is about to begin
IDragHandler – OnDrag – Called on the drag object when a drag is happening
IEndDragHandler – OnEndDrag – Called on the drag object when a drag finishes
IDropHandler – OnDrop – Called on the object where a drag finishes
IScrollHandler – OnScroll – Called when a mouse wheel scrolls
IUpdateSelectedHandler – OnUpdateSelected – Called on the selected object each tick
ISelectHandler – OnSelect – Called when the object becomes the selected object
IDeselectHandler – OnDeselect – Called on the selected object becomes deselected
IMoveHandler – OnMove – Called when a move event occurs (left, right, up, down, ect)
ISubmitHandler – OnSubmit – Called when the submit button is pressed
ICancelHandler – OnCancel – Called when the cancel button is pressed
可见插件的实现和底层还是有重叠的部分,可以借鉴插件手势实现部分, 然后继承BaseInputModule在Process时实现统一处理和特定功能.
特殊的, 对于继承Selectable的Button/InputFeild等可交互组件, 会被设置到EventSystem的currentSelectedGameObject作为当前选中, 设置时机:
- InputModule被激活时(如窗口重新获得焦点)
- 当设置interactable = false时如果当前组件为选中组件会置空选中
- 在OnPointerDown时, 会设置当前组件为选中组件
- 手动调用组件Select()方法设置选中
摇杆原理简述:
摇杆独立于EasyTouch那套, 使用了ugui的EventSystem.
对于动态摇杆(拖拽固定区域时出现摇杆), 多了一个步骤, 首先判断Touch位置是否在响应摇杆的区域内, 如果在则显示摇杆.
显示摇杆后, 手指点击到了摇杆, 会触发注册的OnPointerEnter /OnPointerDown /OnDrag 等事件, OnPointerDown 时记录pinterId(fingerId)以便响应正确对应手指拖拽,在OnDrag时计算摇杆相对于点击位置的偏移量, 之后在LateUpdate时 计算一个(偏移量/半径)相对值供外部使用.零散的还涉及事件派发/模拟摇杆等
版权属于: CrazyStone Entertainment
原文地址: https://www.crazystonent.com/2020/10/01/unity-eventsystem/
转载时必须以链接形式注明原始出处及本声明。