重写带点击事件的CCSprite

要想CCSprite具有点击事件,需要继承CCTargetedTouchDelegate(单点)或者CCStandardTouchDelegate(多点),CCTargetedTouchDelegate和CCStandardTouchDelegate都继承自

CCTouchDelegate

然后在CCSprite的OnEnter中添加

CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,-129,true);

在OnExit中添加

CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);

重写

virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);  

virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);  

virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); 

 

例:

#ifndef _CUSTOMER_SPRITE_H_
#define _CUSTOMER_SPRITE_H_
#include "cocos2d.h"
USING_NS_CC;
class SpriteClickListener{
public:
	virtual void spriteClicked() = 0;
};
class CustomSprite:public CCSprite,public CCTargetedTouchDelegate
{
public:
	void onEnter();
	void onExit();
	static CustomSprite * createWithFile(const char * fileName);
	virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);  
	virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);  
	virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);  
	void setOnClickListener(SpriteClickListener * listener);
private:
	SpriteClickListener * listener;
};
#endif

 

#include "CustomSprite.h"
void CustomSprite::onEnter()
{
	CCSprite::onEnter();
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,-129,true);
}
void CustomSprite::onExit()
{
	CCSprite::onExit();
	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}
CustomSprite * CustomSprite::createWithFile(const char * fileName)
{
	CustomSprite *pobSprite = new CustomSprite();
	if (pobSprite && pobSprite->initWithFile(fileName))
	{
		pobSprite->autorelease();
		return pobSprite;
	}
	CC_SAFE_DELETE(pobSprite);
	return NULL;
}
void CustomSprite::setOnClickListener(SpriteClickListener * listener)
{
	this->listener = listener;
}
bool CustomSprite::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
	//CCLOG("spriteClicked");
	listener->spriteClicked();
	return true;
}
void CustomSprite::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{

}
void CustomSprite::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{

}

 使用:

继承SpriteClickListener

重写

virtual void spriteClicked();

 

CustomSprite *spriteClose = CustomSprite::createWithFile("CloseNormal.png");
spriteClose->setPosition(CCPointMake(100,200));
spriteClose->setOnClickListener(this);
this->addChild(spriteClose);

 

 

你可能感兴趣的:(Sprite)