首页 > 代码库 > cocos2d-x CCSprite 精灵监听点击事件
cocos2d-x CCSprite 精灵监听点击事件
参考文章:
cocos2d-x 精灵监听点击事件
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){ }
本文出自 “漫步雨桥” 博客,请务必保留此出处http://chenjohney.blog.51cto.com/4132124/1433327
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。