cocos2d subclassing sprite to handle touch?

六眼飞鱼酱① 提交于 2019-11-30 08:52:46

问题


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?


回答1:


it is better and much more clear to handle touches in one place. but i think, no one can bar you to do this




回答2:


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
}



回答3:


In cocos2d-x 3.0 alpha you can try this:

auto listener = EventListenerTouchOneByOne::create();

listener->setSwallowTouches(true);

listener->onTouchBegan = [&](Touch* touch, Event* event){

    if (this->getBoundingBox().containsPoint(this->convertTouchToNodeSpace(touch))) {
        return true;
    }
    return false;

};

Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);



回答4:


You do not need to subclass sprites to detect touch.

Here, Follow this LINK its a nice place to get started with Cocos2d



来源:https://stackoverflow.com/questions/11354689/cocos2d-subclassing-sprite-to-handle-touch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!