参考文章:
http://labs.easymobi.cn/?p=5167
实现过程,实现CCTouchDelegate接口,在enter 的时候添加监听,exit 和析构时移除监听,点击时将touch 的坐标转化为相对精灵的坐标,如果是否在精灵的范围内,则响应点击。主要是参考前面两篇文章中的例子,不同的地方在判断区域,个人觉得太复杂。所以稍微修改了下,看起来更容易理解。
PianoTile.h
class PianoTile : public cocos2d::CCSprite,public cocos2d::CCTouchDelegate { public: PianoTile(); ~PianoTile(); //life cycle virtual void onEnter(); virtual void onExit(); //touch virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); };
PianoTile.cpp
#include "PianoTile.h" USING_NS_CC; #pragma mark - Public Methods PianoTile::~PianoTile() { CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this); _delegate = NULL; } #pragma mark Lifecyle void PianoTile::onEnter(){ CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, false); CCSprite::onEnter(); } void PianoTile::onExit(){ CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this); CCSprite::onExit(); } #pragma mark Touch Delegate bool PianoTile::ccTouchBegan(CCTouch *pTouche, CCEvent *pEvent){ CCPoint touchLocation = pTouche->getLocation(); CCPoint localPoint = convertToNodeSpace(touchLocation); CCRect rect = CCRectMake(0, 0, boundingBox().size.width, boundingBox().size.height); bool isTouched = rect.containsPoint(localPoint); if (isTouched && _delegate) { _delegate->pianoTileClick(this); } return isTouched; } void PianoTile::ccTouchEnded(CCTouch *pTouche, CCEvent *pEvent){ }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。