cocos2d-x 3.0 触摸机制的使用

来源:互联网 发布:unity3d汉化版 编辑:程序博客网 时间:2024/05/31 04:04

 http://blog.csdn.net/decajes/article/details/38233645


 cocos2d-x 3.0版本的事件分发的机制较之之前的版本进行了修改,把事件处理的逻辑分离出来,并通过不同的事件监听器来监听不同的事件。当一个节点收到了事件,就会指派一个事件分发器_eventDispatcher专门来分发这些事件。对于触摸来说,大概的过程就是我们先创建一个对应触摸事件的监听器,然后覆盖触摸事件的函数,并把它们绑定到监听器,然后可以设置一下这个监听器的属性,最后把监听器添加到分发器之中,系统就会自动进行触摸事件的处理。    

 

       我们先看看单点触摸的使用,下面是源代码中关于单点触摸监听器的类,可以看到

[cpp] view plaincopy
  1. class EventListenerTouchOneByOne: public EventListener  
  2. {  
  3. public:  
  4.     static const std::string LISTENER_ID;  
  5.     static EventListenerTouchOneByOne* create();  
  6.     virtual~EventListenerTouchOneByOne();  
  7.     void setSwallowTouches(bool needSwallow);  
  8.     bool isSwallowTouches();  
  9.     ///Overrides  
  10.     virtual EventListenerTouchOneByOne* clone() override;  
  11.     virtual bool checkAvailable() override;  
  12.     //  
  13. public:  
  14.     std::function<bool(Touch*, Event*)>onTouchBegan;  
  15.     std::function<void(Touch*, Event*)>onTouchMoved;  
  16.     std::function<void(Touch*, Event*)>onTouchEnded;  
  17.     std::function<void(Touch*, Event*)> onTouchCancelled;  
  18. private:  
  19.     EventListener TouchOneByOne();  
  20.     bool init();  
  21.     std::vector<Touch*>_claimedTouches;  
  22.     bool _needSwallow;  
  23.     friend class EventDispatcher;  
  24. };</span>  

这个类看上去比较容易理解,下面我们用代码来演示一下怎么使用。在HelloWorld的init函数中注册监听器并添加到事件分发器中去。

[cpp] view plaincopy
  1. //添加一个测试的精灵  
  2.     autoonion = Sprite::create("onion.png");  
  3.     onion->setPosition(Point(visibleSize.width/2, visibleSize.height/2));  
  4.     onion->setScale(0.2);  
  5.     this->addChild(onion);  
  6.    
  7.     //创建一个触摸监听器,这里使用单点触摸事件  
  8.     autoTouchListenr = EventListenerTouchOneByOne::create();  
  9.     //设置吞噬为true,不让触摸往下传递  
  10.     TouchListenr->setSwallowTouches(true);  
  11.     //和回调函数绑定  
  12.     TouchListenr->onTouchBegan= CC_CALLBACK_2(HelloWorld::onTouchBegan,this);  
  13.     TouchListenr->onTouchMoved= CC_CALLBACK_2(HelloWorld::onTouchMoved,this);  
  14.     TouchListenr->onTouchEnded= CC_CALLBACK_2(HelloWorld::onTouchEnded,this);  
  15.     //添加监听器到事件分发器中  
  16.     _eventDispatcher->addEventListenerWithSceneGraphPriority(TouchListenr,onion);  

下面我们覆盖单点触摸中提供的触摸函数:

[cpp] view plaincopy
  1. bool HelloWorld::onTouchBegan(Touch* touch, Event* event)  
  2. {  
  3.     //获取精灵对象并取得精灵的矩阵  
  4.     autosprite = static_cast<Sprite*>(event->getCurrentTarget());  
  5.     Rect rect = sprite->getBoundingBox();  
  6.     //获取触摸点的坐标  
  7.     Point point = touch->getLocation();  
  8.     //判断触摸点是否在精灵的矩阵范围内  
  9.     if(rect.containsPoint(point))  
  10.     {  
  11.        return true;  
  12.     }  
  13.     return false;  
  14. }  
  15. void HelloWorld::onTouchMoved(Touch* touch, Event* event)  
  16. {  
  17.     //获取精灵对象  
  18.     autosprite = static_cast<Sprite*>(event->getCurrentTarget());  
  19.     //改变精灵的位置  
  20.     sprite->setPosition(sprite->getPosition()+ touch->getDelta());  
  21. }  
  22. void HelloWorld::onTouchEnded(Touch* touch, Event* event)  
  23. {  
  24.     CCLog("touch end!");  
  25. }  

点击调试运行,可以在屏幕中拉动所测试的精灵,如下图:


       在上面的例子中我们看到了,传递过来的参数主要有Touch* touch和Event* event,我们可以进入源代码中查看他们的作用。Touch类是继承了REF,查看源代码中的主要成员如下:

[cpp] view plaincopy
  1. /**returns the current touch location in OpenGL coordinates */  
  2.     Point getLocation() const;  
  3.     /**returns the previous touch location in OpenGL coordinates */  
  4.     Point getPreviousLocation() const;  
  5.     /**returns the start touch location in OpenGL coordinates */  
  6.     Point getStartLocation() const;  
  7.     /**returns the delta of 2 current touches locations in screen coordinates */  
  8.     Point getDelta() const;  
  9.     /**returns the current touch location in screen coordinates */  
  10.     Point getLocationInView() const;  
  11.     /**returns the previous touch location in screen coordinates */  
  12.     Point getPreviousLocationInView() const;  
  13.     /**returns the start touch location in screen coordinates */  
  14.     Point getStartLocationInView() const;  

       也就是Touch传入的是触摸点的坐标位置,并且Touch类为我们提供一些坐标的写法,那么我们就方便很多了。譬如上面例子中的触摸移动时,Touch就为我提供一个getDelta()来计算点的位移。

而对于Event类,主要是传入处理的对象,看源代码有以下主要成员:

[cpp] view plaincopy
  1. /**Gets the event type */  
  2.    inline Type getType() const { return_type; };  
  3.    /**Stops propagation for current event */  
  4.    inline void stopPropagation() { _isStopped = true; };  
  5.     
  6.    /**Checks whether the event has been stopped */  
  7.    inline bool isStopped() const { return_isStopped; };  
  8.     
  9.    /**@brief Gets current target of the event 
  10.     *  @return The target with which the eventassociates. 
  11.     *  @note It onlys be available when the eventlistener is associated with node. 
  12.     *        It returns 0 when the listener isassociated with fixed priority. 
  13.     */  
  14.    inline Node* getCurrentTarget() { return_currentTarget; };  

         那么我们在处理触摸对象的时候和例子那样通过getCurrentTarget()来获取对象并处理即可。

         另一方面,我们在把监听器添加到事件分发器的时候,会看到代码提示两种方法,一个为:addEventListenerWithSceneGraphPriority,另一个为addEventListenerWithFixedPriority。同样可以查看源代码如下:

[cpp] view plaincopy
  1. /**Adds a event listener for a specified event with the priority of scene graph. 
  2.     *  @param listener The listener of a specifiedevent. 
  3.     *  @param node The priority of the listener isbased on the draw order of this node. 
  4.     *  @note The priority of scene graph will be fixed value 0. So the order oflistener item 
  5.     *          in the vector will be ' <0, scenegraph (0 priority), >0'. 
  6.     */  
  7.    voidaddEventListenerWithSceneGraphPriority(EventListener*listener, Node* node);  
  8.   
  9.    /**Adds a event listener for a specified event with the fixed priority. 
  10.     *  @param listener The listener of a specifiedevent. 
  11.     *  @param fixedPriority The fixed priority ofthe listener. 
  12.     *  @note A lower priority will be called beforethe ones that have a higher value. 
  13.     *        0 priority is forbidden for fixedpriority since it's used for scene graph based priority. 
  14.     */  
  15.    voidaddEventListenerWithFixedPriority(EventListener*listener, int fixedPriority);  

       根据注释可以知道,前者的触发优先级是按照第二个参数中的node的显示顺序来确定的,而且默认的fixedPriority为0,也就是如果精灵位置靠前,则会优先响应触摸。而后者按照第二个参数的整形变量值的大小来确定的,而且不能为0,值越小那么优先响应触摸。两者除了优先级不一样,移除的过程也有差异。前者会在触摸对象对应的node析构之后系统会帮我们调用移除触摸,但是后者就需要我们手动移除,这一点要注意。

       下面我们可以修改上述例子的代码,添加多两个精灵,然后在分发事件代码中添加:

[cpp] view plaincopy
  1. _eventDispatcher->addEventListenerWithSceneGraphPriority(TouchListenr->clone(),onion2);  
  2. _eventDispatcher->addEventListenerWithSceneGraphPriority(TouchListenr->clone(),onion3);  

       点击运行可以测试一下,没有问题。要是想使用addEventListenerWithFixedPriority的方式的话,虽然可以自定义优先级,但是由于没有绑定node对象,所以还需要在触摸函数中引入需要控制的对象才行。但是最后别忘了使用_eventDispatcher->removeEventListener(listerName);来实现监听器的移除。

 

       多点触摸和单点触摸类似,看下面多点触摸监听器的源码。

[cpp] view plaincopy
  1. class EventListenerTouchAllAtOnce: public EventListener  
  2. {  
  3. public:  
  4.     static const std::string LISTENER_ID;  
  5.      
  6.     static EventListenerTouchAllAtOnce* create();  
  7.     virtual ~EventListenerTouchAllAtOnce();  
  8.      
  9.     ///Overrides  
  10.     virtua lEventListenerTouchAllAtOnce* clone() override;  
  11.     virtual bool checkAvailable() override;  
  12.     //  
  13. public:  
  14.     std::function<void(conststd::vector<Touch*>&,Event*)> onTouchesBegan;  
  15.     std::function<void(conststd::vector<Touch*>&,Event*)> onTouchesMoved;  
  16.     std::function<void(conststd::vector<Touch*>&,Event*)> onTouchesEnded;  
  17.     std::function<void(conststd::vector<Touch*>&,Event*)> onTouchesCancelled;  
  18.      
  19. private:  
  20.    EventListener TouchAllAtOnce();  
  21.     bool init();  
  22. private:  
  23.      
  24.     friend class EventDispatcher;  
  25. };  

    可以发现多点触摸就是传入多个Touch对象而已,然后处理的时候可以遍历vector<Touch*>来逐个处理每一个点,例子可以参考源码自带的例子MutiTouchTest。


    文章写到这里为止,如有理解不当,请不吝赐教,谢谢。

0 0