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. tableindex

    在写代码的时候,失焦的第一反应便是ng-blur,没想到在一个标签上其作用了,多加了几个标签没反应,于是发现了tableindex,写的代码列子如下,希望可以帮助你: <img src='{{a ...

  2. 用python2.7,采集新浪博客

    #coding=utf-8 #新浪博客 import urllib import re import os url=['']*1500 #每一骗博客的地址 title=['']*1500 #每一篇博客 ...

  3. Linux环境下Oracle数据库启动停止命令

    切换root至oracle数据库账号 su – oracle 查看数据库服务状态: ps -ef |grep oracle netstat –an|grep 1521 查看数据库监听状态: [orac ...

  4. SSH 动态端口forwarding是如何工作的

    好久没有来了,实在是太懒. 经常用SSH的动态端口forwarding 来FQ,使用像这样的命令: ssh -D 9999 -f -C -q -N sshHost.somewhere.com 这个命令 ...

  5. MySql如何编写高效的SQL

    最近应团队要求,研究整理了下,mysql相关的优化,有些是根据实际java项目中碰到的情况经验之谈.欢迎讨论~ SQL 语言是一种强大而且灵活的语言,在使用 SQL 语言来执行某个关系查询的时候,用户 ...

  6. Sensor(ORIENTATION)

    package com.example.sensor01; import java.util.List; import android.hardware.Sensor; import android. ...

  7. Java IO4:字符编码

    前言 字符编码,这本不属于IO的内容,但字节流之后写的应该是字符流,既然是字符流,那就涉及一个"字符编码的"问题,考虑到字符编码不仅仅是在IO这块,Java中很多场景都涉及到这个概 ...

  8. Nim语言的模块化编程

    前言 Nim支持把一大段程序分成若干个模块 一个模块就是一个源代码文件 每个模块都拥有它自己的名称空间 模块化可以起到封装(信息隐藏)和分步编译的作用 一个模块可以通过import语句获得另一个模块的 ...

  9. windbg 基础命令实战 - 简单程序破解

    以前玩游戏遇到一些实在过不去的管卡,经常会找一些游戏修改软件来修改游戏,让自己变得无比强大,将boss一路砍瓜切菜过足游戏瘾.其实游戏修改软件的功能大多都比较简单,我们可以通过windbg的一些简单命 ...

  10. 使用decode函数实现统计

          从上个星期起就在开始做统计图,各种统计图,昨天做的统计效果图如下:       在这里要根据工作平台和机构做统计,其中当字段A等于某个值时需要统计起来,也就是说假设等于2时需要做统计,字段 ...