问题
I've just started using Cocos 2D-X in Xcode.
I'm trying to make a balloon popping game in order to learn the Cocos 2D-X library. So far, I'm able to show sprites and make them move. As for touch, I'm able to get the touch coordinates (and print it out on the console).
Now, what I want to do is to have the balloons (a CCSprite
object) "pop" (be removed from the layer). I'm looking around for solutions and one of them is to check if the touch location is in the CCSprite
rect. But all the things that I found are either outdated or written in Objective C.
How do I determine if the touch location is within the rect of the balloon? Are there other ways aside from this method?
Thanks a lot.
EDIT: I did it by putting the balloons in an array and checking if the touch location hits one of the balloons in that array. Now, I'm trying to make a Balloon class and handle it from there. Thanks to all who answered.
回答1:
You are lucky enough because I have a game that use balloons, Below is my code, you can finish the Balloon Class and you can use it the same as CCSprite
Example:
Balloon* blueBalloon = Balloon::spriteWithFile("balloon_blue.png");
this->addChild(blueBalloon);
h file:
#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 file:
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;
}
or you can refer to my code in this post cocos2d subclassing sprite to handle touch?
回答2:
In cocos2d-x 3.0 you can try this:
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);
来源:https://stackoverflow.com/questions/11755431/determine-if-object-is-touched-tapped