两种方法其实都一样,CCLayer也是继承CCTouchDelegate。

1、继承CCTouchDelegate

添加触摸代理

CCTouchDispatcher* pDispatcher = CCDirector::sharedDirector()->getTouchDispatcher();

单点触摸用pDispatcher->addTargetedDelegate();

多点触摸用pDispatcher->addStandardDelegate();

在onExit里把代理移除

CCDirector* pDirector = CCDirector::sharedDirector();

pDirector->getTouchDispatcher()->removeDelegate(this);

重写触摸处理

a、单点触摸处理

virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);

virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);

virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);

virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);

b、多点触摸处理

virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);

virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);

virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);

virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent);

2、继承CCLayer

重写onEnter、onExit函数

xxx::onEnter()

{

setTouchEnabled(true);

setTouchMode(kCCTouchesOneByOne单点、kCCTouchesAllAtOnce多点);

CCLayer::onEnter();

}

xxx::onExit()

{

CCLayer::onExit();

}

重写触摸处理

a、单点触摸处理

virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);

virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);

virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);

virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);

b、多点触摸处理

virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);

virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);

virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);

virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent);

还有触摸优先级的设置等,另外单点触摸的ccTouchBegan函数里返回true可以禁止触摸向下传递。

05-28 23:41