Cocos2d-x3.0触摸

来源:互联网 发布:javascript推箱子游戏 编辑:程序博客网 时间:2024/04/29 16:27


cocos2d-x 3.0开始采用C++11,并开始脱离OC风格,在触摸处理上也作出了改变

C++11带来了Lambda表达式(匿名函数),它将简化程序编写,可使代码更清晰易懂

在旧2.x版本的触摸机制之中,是需要重写相关虚函数

在新的版本中,触摸机制进行了修改,你可以随时修改事件对象,还可以使用Lammbda表达式(匿名函数),还可以移除监听器等


--------------------------------------------------------

事件监听器:封装您的事件处理代码。    
事件调度程序:通知用户事件的监听器。        
事件对象:包含关于事件的信息。               

--------------------------------------------------------


创建监听器

    ///创建单击事件监听者   ( EventListenerTouchAllAtOnce  则是多点)    auto touchListener=EventListenerTouchOneByOne::create();    ///setSwallowTouches  使当前层的touch事件不会传递给它之下的层    touchListener->setSwallowTouches(true);


事件对象绑定

///Lambda表达式  PS:这里的[=] 代表 截取外部作用域中所有变量,并拷贝一份在函数体中使用,详情可以翻阅其他资料    touchListener->onTouchBegan=[=](Touch* touch, Event* evnet)    {        cocos2d::Point  s_PLocation=touch->getLocation();        addSpriteAtArcRandom(s_PLocation);        return true;    };    ///C++11 bind模板函数(其实也就是CC_CALLBACK_XX宏)    touchListener->onTouchEnded=std::bind(&HelloWorld::onTouchEnded, this,std::placeholders::_1,std::placeholders::_2);    touchListener->onTouchMoved=std::bind(&HelloWorld::onTouchMoved, this,std::placeholders::_1,std::placeholders::_2);


将事件监听器加入调度器中


    auto dispatcher=Director::getInstance()->getEventDispatcher();    ///添加事件监听器,并设置优先级,PS:既然有添加,当然有移除(removeEventListeners(指定对象),removeEventListenersForType(指定类型)等),嘿嘿,  比以前方便了不少    dispatcher->addEventListenerWithFixedPriority(touchListener, 1);

(1)addEventListenerWithSceneGraphPriority:注册监听事件,监听优先级按绘制顺序来

(2)addEventListenerWithFixedPriority:注册监听事件,可以设置事件的监听的优先级别

(3)addCustomEventListener:注册自定义监听事件,并且监听优先级固定为1


可参考:  http://www.cocos2d-x.org/docs/manual/framework/native/input/event-dispatcher/en


0 0