确定对象是否被触摸/轻敲

我刚开始在Xcode中使用Cocos 2D-X。

我试图做一个气球popup游戏,以了解Cocos 2D-X库。 到目前为止,我能够显示精灵并使其移动。 至于触摸,我可以得到触摸坐标(并在控制台上打印出来)。

现在,我想要做的是让气球(一个CCSprite对象)“popup”(从图层中删除)。 我四处寻找解决scheme,其中之一是检查触摸位置是否在CCSprite矩形。 但是我发现的所有东西都是过时的或者写在Objective C中的

我如何确定触摸位置是否在气球的矩形内? 除了这个方法还有其他的方法吗?

非常感谢。

编辑 :我把气球放在一个数组中,并检查触摸位置是否碰到该数组中的一个气球。 现在,我正在尝试做一个气球class,并从那里处理它。 感谢所有回答。

你很幸运,因为我有一个使用气球的游戏,下面是我的代码,你可以完成气球类,你可以使用它与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; } 

或者你可以参考我的代码在这个postcocos2d子类化精灵处理触摸?

在cocos2d-x 3.0中,你可以试试这个:

 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);