可能在制作游戏的过程中,用到sprite,但是它本省的方法有限,我需要再次扩充它,那么我们可以通过继承得到自定义的sprite:
定义如下:
#ifndef MYSPRITEBASE_H_
#define MYSPRITEBASE_H_
#include "cocos2d.h"
USING_NS_CC;
class MySprite : public CCSprite, public CCStandardTouchDelegate
{
public:
MySprite();
~MySprite();
public:
CCRect rect();
bool initWithTexture(CCTexture2D* aTexture);
void onEnter();
void onExit();
bool containsTouchLocation(CCTouch* touch);
void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);
void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);
void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);
CCObject* copyWithZone(CCZone *pZone);
void touchDelegateRetain();
void touchDelegateRelease();
static MySprite *paddleWithTexture(CCTexture2D* aTexture);
static MySprite *create(CCTexture2D *pTexture);
}; // end of MySprite
#endif //MYSPRITEBASE_H_
在这里我们采用的消息类是用到的:CCStandardTouchDelegate类。
当然也可以用:CCTargetedTouchDelegate
具体实现:
#include "MySpriteBase.h"
MySprite::MySprite() {
CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this, 0);
}
MySprite::~MySprite() {
}
CCRect MySprite::rect() {
CCSize s = getTexture()->getContentSize();
return CCRectMake(s.width / 2, -s.height / 2, s.width, s.height);
}
bool MySprite::initWithTexture(CCTexture2D* aTexture) {
if( CCSprite::initWithTexture(aTexture) )
{
return true;
}
return false;
}
MySprite *MySprite::create(CCTexture2D *pTexture) {
MySprite *pobSprite = new MySprite();
if (pobSprite && pobSprite->initWithTexture(pTexture))
{
pobSprite->autorelease();
return pobSprite;
}
CC_SAFE_DELETE(pobSprite);
}
void MySprite::onEnter() {
CCSprite::onEnter();
}
void MySprite::onExit() {
CCSprite::onExit();
}
bool MySprite::containsTouchLocation(CCTouch* touch) {
return true;
}
void MySprite::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) {
}
void MySprite::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent) {
}
void MySprite::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) {
}
CCObject* MySprite::copyWithZone(CCZone *pZone) {
this->retain();
return this;
}
void MySprite::touchDelegateRetain() {
this->retain();
}
void MySprite::touchDelegateRelease() {
this->release();
}
MySprite* paddleWithTexture(CCTexture2D* aTexture) {
MySprite* pPaddle = new MySprite();
pPaddle->initWithTexture( aTexture );
pPaddle->autorelease();
return pPaddle;
}