cocos2d-x CCSprite 精灵监听点击事件

时间:2021-06-08 05:10:58

参考文章:

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 MethodsPianoTile::~PianoTile(){    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);    _delegate = NULL;}#pragma mark Lifecylevoid PianoTile::onEnter(){    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, false);    CCSprite::onEnter();}void PianoTile::onExit(){    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);    CCSprite::onExit();}#pragma mark Touch Delegatebool 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