事件处理机制
很多图形用户技术中,事件处理机制一般都有三个重要的角色:事件、事件源、事件处理者。事件源是事件发生的场所,通常就是各个视图或控件,事件处理者是接收事件并对其进行处理的一段程序
-
事件
事件类是Event,类图如下
子类只要有EventTouch(触摸事件)、EventMouse(鼠标事件)、EventKeyboard(键盘事件)、EventAcceleration(加速度事件)、EventCustom(自定义事件)
-
事件源
事件源是cocos2d-x中的精灵、层、菜单等节点对象
-
事件处理者
cocos2d-x中事件处理者是事件监听器类EventListener,
子类有 EventListenerTouchOneByOne(单点触摸事件监听器)、EventListenerTouchAllAtOnce(多点触摸事件监听器)、EventListenerKeyboard(键盘事件监听器)、EventListenerMouse(鼠标事件监听器)、EventListenerAcceleration(加速度事件监听器)、EventListenerCustom(自定义事件监听器)
事件分发器
从前面的类图和命名上可以看出事件监听器与事件具有对应关系,例如,键盘事件只能由键盘事件监听器处理,它们之间需要在程序中建立关系。这种关系的建立过程被称为注册监听器,Cocos2d-x提供一个事件分发器(EventDispatcher)负责管理这种关系,具体说事件分发器负责注册监听器、注销监听器和事件分发
EventDispatcher 类采用单例模式设计,通过Director::getInstance()->getEventDispatcher()语句获得事件分发器对象
EventDispatcher 类中注册事件监听器到事件分发器函数如下:
void addEventListenerWithFixedPriority(EventListener *listener,int fixedPriority);// 指定固定事件的优先级注册监听器,事件优先级决定事件响应的优先级别,值越小优先级别越高
void addEventListenerWithSceneGraphPriority(EventListener *listener,Node *node);// 把精灵显示优先级别作为事件优先级,
/*
当不在进行事件响应时,应该注销事件监听器
*/
void removeEventListener(EventListener* listener);// 注销指定事件监听器
void removCustomEventListeners(const std::string& customEventName);// 注销自定义事件监听器
void removeAllEventListeners();//注销所有事件监听器,需要注意,使用该函数后,菜单亦不能响应事件了
触摸事件
触摸事件从时间和空间两方面考虑
-
时间
有按下、移动、抬起等阶段
触摸事件有两个事件监听器:
EventListenerTouchOneByOne 和 EventListenerTouchAllAtOnce,分别对应单点触摸和多点触摸
-
空间
空间方面就是每个触摸点对象包含了当前位置信息,以及之前的位置信息
/* 获取触摸点之前的位置 */ Vec2 getPreviousLocationInView();// UI坐标 Vec2 getPreviousLocation();// OpenGL /* 可以获得触摸点当前的位置信息 */ Vec2 getLocationInViewd();// UI坐标 Vec2 getLocation();// 获取OpenGL
Lambda表达式
略
加速度计和加速度事件
-
加速度计
是一种能够感应设备一个方向上线性加速度的传感器,采用的坐标是右手坐标系。
使用加速度计
Device::setAccelerometerEnabled(true);