How can I inherit CCSprite and write my init() ,onEnter() and onExit()

How can I inherit CCSprite and write my init() ,onEnter() and onExit()
0.0 0



I try to write a touchable CCSprite to handle the touch event by sprite itself.

So I make a class TouchSprite and inherit from cocos2d::CCSprite and my codes are something like these:

class TouchSprite : public cocos2d::CCSprite, public CCTargetedTouchDelegate
virtual bool init();
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);

but when I put a breakpoint under my implementation of init(), it never stops.

I try to trace the code, and I found it does go into the CCSprite::init().

BTW, I use the CCSprite::spriteWithSpriteFrameName(“test.png”) to new the instance of my sprite.

Maybe I need to write a static TouchSprite::spriteWithSpriteFrameName(const char* filename) and do the init() there by myself ??

C++ equivalent of iOS instruction "if ((self = [super initWithSpriteFrameName:@"myimage.png"]))" ??

I already find a solution for my question.

After I use below codes, all the init(), onEnter() and onExit() functions work as expected.

TouchSprite* touchsprite = new TouchSprite();

Hope can help someone like me.


Oh, here’s caused by a difference between c*+ & objc
When your TouchSprite inherits static method CCSprite::spriteWithSpriteFrameName, it calls CCSprite::spriteWithSpriteFrame, and finally invokes init in CCSprite::initWithTexture.
The problem is here. In C*+ class, init() or this->init() will invoke the “init” method in the current class, which is your parent class; unless we force to ((TouchSprite*)this)->init() in CCSprite.cpp. But obviously we cannot do this.
And in objc class, [self init] will invoke the “init” from your child class TouchSprite.


Thank you for your answer.

I just aware this difference after I throw the question, that’s why I change my code to use the new instead and init after.

That’s really helps, thank you again.