对Touch事件的获取与处理可以使用CCLayer, CCMenuItem等,但是如果我们需要一个虚拟按键或者需要对特定精灵进行拖动等等,我们就需要自定义Touch类。
自定义Touch事件处理类重要的步骤是:
1. 继承CCTargetedTouchDelegate
2. 添加addTargetedDelegate(pDelegate, nPriority, bSwallowsTouches),来获取Touch事件,第二个参数是优先级,越高越优先。
3. 根据自己的需要override Touch事件处理函数:
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
如下是实例:这里添加一个自定义的Button到场景层。
- #include <cocos2d.h>
- USING_NS_CC;
- class MyButton : public CCNode, public CCTargetedTouchDelegate
- {
- public:
- MyButton(void);
- ~MyButton(void);
- virtual void onEnter();
- virtual void onExit();
- virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
- virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
- virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
- virtual bool init();
- CREATE_FUNC(MyButton);
- private:
- CCSprite *m_ShowPic;
- };
- #include "MyButton.h"
- MyButton::MyButton(void):m_ShowPic(NULL)
- {
- }
- MyButton::~MyButton(void)
- {
- }
- bool MyButton::init()
- {
- bool bRet = false;
- do
- {
- CCSize winSize = CCDirector::sharedDirector()->getWinSize();
- m_ShowPic = CCSprite::create("share.png");
- m_ShowPic->setPosition(ccp(winSize.width/2, winSize.height/2));
- this->addChild(m_ShowPic);
- bRet = true;
- } while(0);
- return bRet;
- }
- void MyButton::onEnter()
- {
- CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
- CCNode::onEnter();
- }
- void MyButton::onExit()
- {
- CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
- CCNode::onExit();
- }
- bool MyButton::ccTouchBegan(CCTouch* touch, CCEvent* event)
- {
- CCLog("MyButton Touch Began!");
- return true;
- }
- void MyButton::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
- {
- CCLog("MyButton Touch Move!");
- }
- void MyButton::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
- {
- CCLog("MyButton Touch Ended!");
- }
将以下代码其添加到HelloWorldScene::init中,
- // Add MyButton
- MyButton *button = MyButton::create();
- this->addChild(button, 10);
- button->setPosition(CCPointZero);
运行测试:
在屏幕中点击可以看到Output中显示了我们的CCLog提示
可是我们没有点击到图片时也会提示出CCLog,这并不是我们想要的。
那么我们就需要添加自己需要的Touch事件处理代码了:
例如如下:
-
- bool MyButton::ccTouchBegan(CCTouch* touch, CCEvent* event)
- {
- CCPoint position = convertTouchToNodeSpaceAR(touch);
- if (!m_ShowPic->boundingBox().containsPoint(position))
- return false;
- CCLog("MyButton Touch Began!");
- // add your code...
- return true;
- }
- void MyButton::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
- {
- CCLog("MyButton Touch Move!");
- // add your code...
- }
- void MyButton::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
- {
- CCLog("MyButton Touch Ended!");
- // add your code...
- }