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

发布时间:2020-07-06 09:48:41 作者:chenjohney
来源:网络 阅读:3780

参考文章:

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){
    
}


推荐阅读:
  1. Cocos2d-x《赵云要格斗》--虚拟摇杆控制精灵上下左右运动
  2. 十:Cocos2d-x缓存机制

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

精灵 touch cocos2d-x

上一篇:EV证书合适用于哪种企业

下一篇:SSL证书到期要更新的理由

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》