你很幸运,因为我有一个使用气球的游戏,下面是我的代码,你可以完成气球类,你可以像 CCSprite 一样使用它
例子:
Balloon* blueBalloon = Balloon::spriteWithFile("balloon_blue.png");
this->addChild(blueBalloon);
h 文件:
#include "cocos2d.h"
using namespace cocos2d;
class Balloon : 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文件:
void Balloon::onEnter(){
CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, true);
CCSprite::onEnter();
}
void Balloon::onExit(){
CCTouchDispatcher::sharedDispatcher()->removeDelegate(this);
CCSprite::onExit();
}
void Balloon::ccTouchMoved(CCTouch* touch, CCEvent* event){
//do what you want
}
void Balloon::ccTouchEnded(CCTouch* touch, CCEvent* event){
//do your job here
}
bool Balloon::ccTouchBegan(CCTouch* touch, CCEvent* event){
CCPoint touchLocation = this->getParent()->convertTouchToNodeSpace(touch);
if (CCRect::CCRectContainsPoint(this->boundingBox(), touchLocation)) {
this->playBalloonSound();
this->removeFromParentAndCleanup(true);
}
return true;
}
或者你可以参考我这篇文章cocos2d subclassing sprite 中的代码来处理触摸?