EventDispatcher事件分发机制先创建事件,注册到事件管理中心_eventDispatcher,通过发布事件得到响应进行回调,完成事件流。

有五种不同的事件机制:
EventListenerTouch 响应触控事件
EventListenerKeyboard 响应键盘事件
EventListenerAcceleration 响应加速器事件
EventListenMouse 响应鼠标事件
EventListenerCustom 响应自定义的事件

优先权:

  1.优先级越低,越先响应事件

  2.如果优先级相同,则上层的(z轴)先接收触摸事件。

事件监听器的优先级:

  1.addEventListenerWithSceneGraphPriority 的事件监听器优先级是0,而且在 addEventListenerWithFixedPriority 中的事件监听器的优先级不可以设置为 0,因为这个是保留给 SceneGraphPriority 使用的。

  2.另外,有一点非常重要,FixedPriority listener添加完之后需要手动remove,而SceneGraphPriority listener是跟node绑定的,在node的析构函数中会被移除。移除方法:dispatcher->removeEventListener(listener);

事件管理单例获取:
  _eventDispatcher是Node的属性,通过它管理当前节点(场景、层、精灵等)的所有事件的分发。但它本身是一个单例模式值的引用,在Node的构造函数中,通过Director::getInstance()->getEventDispatcher(); 获取,有了这个属性,就能方便的处理事件。

触摸事件:

  

void EventDispatcherTest::funEventTouch(Sprite* sprite)
{
this->_eventDispatcher->removeAllEventListeners(); auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(EventDispatcherTest::onTouchBeganss,this);
listener->onTouchMoved = CC_CALLBACK_2(EventDispatcherTest::onTouchMovedss,this);
listener->onTouchEnded = CC_CALLBACK_2(EventDispatcherTest::onTouchEndedss,this);
listener->onTouchCancelled = CC_CALLBACK_2(EventDispatcherTest::onTouchCancelledss,this);
listener->setSwallowTouches(true);//是否向下传递
this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,sprite);
} bool EventDispatcherTest::onTouchBeganss(Touch* touch,Event* ev)
{
auto target = static_cast<Sprite*>(ev->getCurrentTarget()); Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation());
Size s = target->getContentSize();
Rect rect = Rect(, , s.width, s.height);
  //判断触摸区域是否在目标上
if (rect.containsPoint(locationInNode))
{
label->setString("onTouchBegan......");
target->setOpacity();
return true;
}
return false;
}
void EventDispatcherTest::onTouchMovedss(Touch* touch,Event* ev)
{
auto target = static_cast<Sprite*>(ev->getCurrentTarget());
target->setPosition(target->getPosition() + touch->getDelta());
label->setString("onTouchMoved......");
}
void EventDispatcherTest::onTouchEndedss(Touch* touch,Event* ev)
{
auto target = static_cast<Sprite*>(ev->getCurrentTarget());
target->setOpacity();
label->setString("onTouchEnded......");
}
void EventDispatcherTest::onTouchCancelledss(Touch* touch,Event* ev)
{
label->setString("onTouchCancelled......");
}

键盘事件

void EventDispatcherTest::funEventKeyboard()
{
this->_eventDispatcher->removeAllEventListeners(); auto listener = EventListenerKeyboard::create();
listener->onKeyPressed = CC_CALLBACK_2(EventDispatcherTest::onKeyPressedss,this);
listener->onKeyReleased = CC_CALLBACK_2(EventDispatcherTest::onKeyReleasedss,this);
this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this);
} void EventDispatcherTest::onKeyPressedss(EventKeyboard::KeyCode keycode,Event* ev)
{
char txt[] = {};
sprintf_s(txt,"key %d is Pressed!",(int)keycode);
label->setString(txt);
} void EventDispatcherTest::onKeyReleasedss(EventKeyboard::KeyCode keycode,Event* ev)
{
label->setString("key is Released!");
}

鼠标事件

void EventDispatcherTest::funEventMouse(Sprite* sprite)
{
this->_eventDispatcher->removeAllEventListeners(); auto listener = EventListenerMouse::create();
listener->onMouseDown = CC_CALLBACK_1(EventDispatcherTest::onMouseDownss,this);
listener->onMouseMove = CC_CALLBACK_1(EventDispatcherTest::onMouseMovess,this);
listener->onMouseUp = CC_CALLBACK_1(EventDispatcherTest::onMouseUpss,this);
listener->onMouseScroll = CC_CALLBACK_1(EventDispatcherTest::onMouseScrollss,this);
this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,sprite);
} void EventDispatcherTest::onMouseDownss(Event* ev)
{
label->setString("onMouseDown!");
}
void EventDispatcherTest::onMouseMovess(Event* ev)
{
label->setString("onMouseMove!");
}
void EventDispatcherTest::onMouseUpss(Event* ev)
{
label->setString("onMouseUp!");
}
void EventDispatcherTest::onMouseScrollss(Event* ev)
{
label->setString("onMouseScroll!");
}

自定义事件

  

//自定義事件
funEventCustom();
//2秒後派發一次自定義事件,測試
scheduleOnce(schedule_selector(EventDispatcherTest::dispatcherCustomEvents),2.0f);
void EventDispatcherTest::funEventCustom()
{
auto listener = EventListenerCustom::create("custom_event_1",CC_CALLBACK_1(EventDispatcherTest::onEventCustom,this));
this->_eventDispatcher->addEventListenerWithFixedPriority(listener,);//添加到事件分發器
} void EventDispatcherTest::dispatcherCustomEvents(float at)
{
//派發事件custom_event_1 事件內容為字符串custom event test!
this->_eventDispatcher->dispatchCustomEvent("custom_event_1","custom event test!");
} void EventDispatcherTest::onEventCustom(EventCustom* event)
{
auto data = static_cast<char*>(event->getUserData());
label->setString(data);
}

加速器事件

  除了触摸,移动设备上一个很重要的输入源是设备的方向,因此大多数设备都配备了加速计,用于测量设备静止或匀速运动时所受到的重力方向。

重力感应来自移动设备的加速计,通常支持X,Y和Z三个方向的加速度感应,所以又称为三向加速计。在实际应用中,可以根据3个方向的力度大小来计算手机倾斜的角度或方向。

加速计监听器EventListenerAcceleration,其静态create方法中有个Acceleration的参数。Acceleration是一个类,包含了加速计获得的3个方向的加速度。

void EventDispatcherTest::funEventAcceleration()
{
//啟動硬件設備
Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(EventDispatcherTest::onAcceleration,this));
this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this);
} void EventDispatcherTest::onAcceleration(Acceleration* acc,Event* event)
{
char str[]={};
sprintf_s(str,"x:%2d,y:%2d,z:%2d,timestamp:%2d",acc->x,acc->y,acc->z,acc->timestamp);
log(str);
}

示例代码

#ifndef __EventDispatcherTest__
#define __EventDispatcherTest__ #include "cocos2d.h" USING_NS_CC; class EventDispatcherTest : public Layer
{
public:
CREATE_FUNC(EventDispatcherTest);
virtual bool init();
static Scene* createScene();
LabelTTF* label;
void funEventTouch(Sprite* sprite);
void funEventKeyboard();
void funEventMouse(Sprite* sprite);
void funEventCustom();
void funEventAcceleration(); bool onTouchBeganss(Touch* touch,Event* ev);
void onTouchMovedss(Touch* touch,Event* ev);
void onTouchEndedss(Touch* touch,Event* ev);
void onTouchCancelledss(Touch* touch,Event* ev); void onKeyPressedss(EventKeyboard::KeyCode keycode,Event* ev);
void onKeyReleasedss(EventKeyboard::KeyCode keycode,Event* ev); void onMouseDownss(Event* ev);
void onMouseMovess(Event* ev);
void onMouseUpss(Event* ev);
void onMouseScrollss(Event* ev); void dispatcherCustomEvents(float at);
void onEventCustom(EventCustom* event); void onAcceleration(Acceleration* acc,Event* event);
}; #endif

EventDispatcherTest.h

#include "EventDispatcherTest.h"
Scene* EventDispatcherTest::createScene()
{
auto scene = Scene::create();
auto layer = EventDispatcherTest::create();
scene->addChild(layer);
return scene;
} bool EventDispatcherTest::init()
{ Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
label = LabelTTF::create("Hello World", "Arial", );
label->setPosition(Vec2(origin.x + visibleSize.width/,
origin.y + visibleSize.height - label->getContentSize().height));
this->addChild(label, ); auto sprite = Sprite::create("MagentaSquare.png",Rect(,,,));
sprite->setPosition(visibleSize/);
this->addChild(sprite); //funEventTouch(sprite); //觸摸事件
//funEventKeyboard(); //鍵盤事件
//funEventMouse(sprite);//鼠標事件
//funEventAcceleration();//加速器事件 //自定義事件
funEventCustom();
//2秒後派發一次自定義事件,測試
scheduleOnce(schedule_selector(EventDispatcherTest::dispatcherCustomEvents),2.0f);
return true;
} void EventDispatcherTest::funEventTouch(Sprite* sprite)
{
this->_eventDispatcher->removeAllEventListeners(); auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(EventDispatcherTest::onTouchBeganss,this);
listener->onTouchMoved = CC_CALLBACK_2(EventDispatcherTest::onTouchMovedss,this);
listener->onTouchEnded = CC_CALLBACK_2(EventDispatcherTest::onTouchEndedss,this);
listener->onTouchCancelled = CC_CALLBACK_2(EventDispatcherTest::onTouchCancelledss,this);
listener->setSwallowTouches(true);//是否向下传递
this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,sprite);
} bool EventDispatcherTest::onTouchBeganss(Touch* touch,Event* ev)
{
auto target = static_cast<Sprite*>(ev->getCurrentTarget()); Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation());
Size s = target->getContentSize();
Rect rect = Rect(, , s.width, s.height); if (rect.containsPoint(locationInNode))
{
label->setString("onTouchBegan......");
target->setOpacity();
return true;
}
return false;
}
void EventDispatcherTest::onTouchMovedss(Touch* touch,Event* ev)
{
auto target = static_cast<Sprite*>(ev->getCurrentTarget());
target->setPosition(target->getPosition() + touch->getDelta());
label->setString("onTouchMoved......");
}
void EventDispatcherTest::onTouchEndedss(Touch* touch,Event* ev)
{
auto target = static_cast<Sprite*>(ev->getCurrentTarget());
target->setOpacity();
label->setString("onTouchEnded......");
}
void EventDispatcherTest::onTouchCancelledss(Touch* touch,Event* ev)
{
label->setString("onTouchCancelled......");
} void EventDispatcherTest::funEventKeyboard()
{
this->_eventDispatcher->removeAllEventListeners(); auto listener = EventListenerKeyboard::create();
listener->onKeyPressed = CC_CALLBACK_2(EventDispatcherTest::onKeyPressedss,this);
listener->onKeyReleased = CC_CALLBACK_2(EventDispatcherTest::onKeyReleasedss,this);
this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this);
} void EventDispatcherTest::onKeyPressedss(EventKeyboard::KeyCode keycode,Event* ev)
{
char txt[] = {};
sprintf_s(txt,"key %d is Pressed!",(int)keycode);
label->setString(txt);
} void EventDispatcherTest::onKeyReleasedss(EventKeyboard::KeyCode keycode,Event* ev)
{
label->setString("key is Released!");
} void EventDispatcherTest::funEventMouse(Sprite* sprite)
{
this->_eventDispatcher->removeAllEventListeners(); auto listener = EventListenerMouse::create();
listener->onMouseDown = CC_CALLBACK_1(EventDispatcherTest::onMouseDownss,this);
listener->onMouseMove = CC_CALLBACK_1(EventDispatcherTest::onMouseMovess,this);
listener->onMouseUp = CC_CALLBACK_1(EventDispatcherTest::onMouseUpss,this);
listener->onMouseScroll = CC_CALLBACK_1(EventDispatcherTest::onMouseScrollss,this);
this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,sprite);
} void EventDispatcherTest::onMouseDownss(Event* ev)
{
label->setString("onMouseDown!");
}
void EventDispatcherTest::onMouseMovess(Event* ev)
{
label->setString("onMouseMove!");
}
void EventDispatcherTest::onMouseUpss(Event* ev)
{
label->setString("onMouseUp!");
}
void EventDispatcherTest::onMouseScrollss(Event* ev)
{
label->setString("onMouseScroll!");
} void EventDispatcherTest::funEventCustom()
{
auto listener = EventListenerCustom::create("custom_event_1",CC_CALLBACK_1(EventDispatcherTest::onEventCustom,this));
this->_eventDispatcher->addEventListenerWithFixedPriority(listener,);//添加到事件分發器
} void EventDispatcherTest::dispatcherCustomEvents(float at)
{
//派發事件custom_event_1 事件內容為字符串custom event test!
this->_eventDispatcher->dispatchCustomEvent("custom_event_1","custom event test!");
} void EventDispatcherTest::onEventCustom(EventCustom* event)
{
auto data = static_cast<char*>(event->getUserData());
label->setString(data);
} void EventDispatcherTest::funEventAcceleration()
{
//啟動硬件設備
Device::setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(EventDispatcherTest::onAcceleration,this));
this->_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this);
} void EventDispatcherTest::onAcceleration(Acceleration* acc,Event* event)
{
char str[]={};
sprintf_s(str,"x:%2d,y:%2d,z:%2d,timestamp:%2d",acc->x,acc->y,acc->z,acc->timestamp);
log(str);
}

EventDispatcherTest.cpp

Cocos2d-x 3.2 学习笔记(九)EventDispatcher事件分发机制的更多相关文章

  1. Cocos2d-x 学习笔记(15.2) EventDispatcher 事件分发机制 dispatchEvent(event)

    1. 事件分发方法 EventDispatcher::dispatchEvent(Event* event) 首先通过_isEnabled标志判断事件分发是否启用. 执行 updateDirtyFla ...

  2. 多线程学习笔记九之ThreadLocal

    目录 多线程学习笔记九之ThreadLocal 简介 类结构 源码分析 ThreadLocalMap set(T value) get() remove() 为什么ThreadLocalMap的键是W ...

  3. MDX导航结构层次:《Microsoft SQL Server 2008 MDX Step by Step》学习笔记九

    <Microsoft SQL Server 2008 MDX Step by Step>学习笔记九:导航结构层次   SQL Server 2008中SQL应用系列及BI笔记系列--目录索 ...

  4. python3.4学习笔记(九) Python GUI桌面应用开发工具选择

    python3.4学习笔记(九) Python GUI桌面应用开发工具选择 Python GUI开发工具选择 - WEB开发者http://www.admin10000.com/document/96 ...

  5. Go语言学习笔记九: 指针

    Go语言学习笔记九: 指针 指针的概念是当时学C语言时了解的.Go语言的指针感觉与C语言的没啥不同. 指针定义与使用 指针变量是保存内存地址的变量.其他变量保存的是数值,而指针变量保存的是内存地址.这 ...

  6. go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin)

    目录 go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin) zipkin使用demo 数据持久化 go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin ...

  7. iOS学习笔记之触摸事件&UIResponder

    iOS学习笔记之触摸事件&UIResponder 触摸事件 与触摸事件相关的四个方法如下: 一根手指或多根手指触摸屏幕 -(void)touchesBegan:(NSSet *)touches ...

  8. Android程序员事件分发机制学习笔记

    通过问题来学习一个东西是很好的方法.学习Android中View的事件体系,我也通过给自己提问题,在解决问题的同时也就知道了其中原理. 首先来几个问题起步: 什么是事件?什么是事件分发机制? 在我们通 ...

  9. 【Unity游戏开发】用C#和Lua实现Unity中的事件分发机制EventDispatcher

    一.简介 最近马三换了一家大公司工作,公司制度规范了一些,因此平时的业余时间多了不少.但是人却懒了下来,最近这一个月都没怎么研究新技术,博客写得也是拖拖拉拉,周六周天就躺尸在家看帖子.看小说,要么就是 ...

随机推荐

  1. 如何去掉底部的织梦版权信息powered by dedecms

    由于织梦DEDECMS程序6月份的漏洞,很多织梦网站都被黑了,所以大家都在抓紧时间更新系统补丁.但是这次的DEDECMS V5.7版本更新后,在前台网页底部会出现织梦版权信息 “powered by ...

  2. 用canvas制作酷炫射击游戏--part1

    好久没写博客了,因为过年后一直在学游戏制作方面的知识.学得差不多后又花了3个月时间做了个作品出来,现在正拿着这个作品找工作. 作品地址:https://betasu.github.io/Crimonl ...

  3. mysql sql_safe_updates 不支持子查询的更新。

    考虑到开发人员有时候不小心误更新数据,要求线上库的 MySQL 实例都设置 sql_safe_updates=1 来避免没有索引的 update.delete. 结果有一天开发发现下面的一个SQL 没 ...

  4. anyncTask的3个参数

    AnyncTask异步处理数据并将数据应用到视图的操作场合 一  其中包含这几个方法 1 onPreExcute() 初始化控件,例如进度条2 doInBackground() 具体的执行动作请求数据 ...

  5. Asp.net web form url route使用总结

    asp.net web form 使用URL路由 注不是mvc中的路由 一.前台控件使用路由,通过表达式生成url地址,注意给路由参数赋值,防止使用了其他路由表达式值方式1:<asp:Hyper ...

  6. 每周一书-《Bootstrap基础教程》

    首先说明,本周活动有效时间为8月15日到21日.本周为大家送出的书是有电子工业出版,贺臣/陈鹏编著的<Bootsrap基础教程>,为前端入门必读书籍. 下面是从书中摘录的内容. “ Boo ...

  7. 浅谈Excel开发:六 Excel 异步自定义函数

    上文介绍了Excel中的自定义函数(UDF ),它极大地扩展了Excel插件的功能,使得我们可以将业务逻辑以Excel函数的形式表示,并可以根据这些细粒度的自定义函数,构建各种复杂的分析报表. 普通的 ...

  8. .net 时间戳和日期互转

    1.时间戳转日期 public static DateTime IntToDateTime(int timestamp) {     ,,)).AddSeconds(timestamp); } 调用: ...

  9. Node.js刷新session过期时间

    在Node.js中,我们通常使用express-session这个包来使用和管理session,保存服务端和客户端浏览器之间的会话状态.那如何才能实现当用户刷新当前页面或者点击页面上的按钮时重新刷新s ...

  10. MySQL服务器安装配置-非安装版、windows版

    文档以5.6.30版本为例子说明 1. 下载MySQL http://dev.mysql.com/downloads/mysql/5.6.html#downloads 我们可以选择自己所需要的版本.环 ...