Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

cocos2d subclassing sprite to handle touch?

I'm new to the cocos2d(-x) world.

I'd like to detect a touch to a sprite, and tutorials/examples seem to suggest using layer to detect touch and find the approapriate sprite with bounding box.

Is subclassing sprite to allow touch detection generally a bad idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note: This answer might be outdated. I answered this at 2012.

It is not a bad idea. Here is how I do it:

header file:

#include "cocos2d.h"
using namespace cocos2d;
class TouchableSprite : public cocos2d::CCSprite, public CCTargetedTouchDelegate {
    public:
    virtual void onEnter();
    virtual void onExit();
    virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
    virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
    virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
};

cpp file:

#include "TouchableSprite.h"
void TouchableSprite::onEnter(){
    // before 2.0:
    // CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, true);

    // since 2.0: 
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
    CCSprite::onEnter();
}
void TouchableSprite::onExit(){
    // before 2.0:
    // CCTouchDispatcher::sharedDispatcher()->removeDelegate(this);

    // since 2.0:
    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
    CCSprite::onExit();
}
bool TouchableSprite::ccTouchBegan(CCTouch* touch, CCEvent* event){
    //do whatever you want here
    return true;
}
void TouchableSprite::ccTouchMoved(CCTouch* touch, CCEvent* event){
    //do what you want
}
void TouchableSprite::ccTouchEnded(CCTouch* touch, CCEvent* event){
    //do your job here
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...