class Fish : public cocos2d::CCNode, public CCTargetedTouchDelegate {
private:
CCSprite *sprite;
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);
bool containsTouchLocation(CCTouch* touch);
CCRect rect();
/* the rest of your code*/
};
/* cpp file */
void Fish::onEnter(){
CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, true);
CCNode::onEnter();
}
void Fish::onExit(){
CCTouchDispatcher::sharedDispatcher()->removeDelegate(this);
}
bool Fish::ccTouchBegan(CCTouch* touch, CCEvent* event){
/* if you return true then ccTouchEnded will called */
/* if you return false then ccTouchEnded will not be called, and the event will go the parent layer */
CCPoint point = touch->locationInView(touch->view());
point = CCDirector::sharedDirector()->convertToGL(point);
return CCRect::CCRectContainsPoint(rect(), point);
}
void Fish::ccTouchMoved(CCTouch* touch, CCEvent* event){
CCLOG(“Fish ccTouchMoved”);
/* do your stuff here */
}
void Fish::ccTouchEnded(CCTouch* touch, CCEvent* event){
CCLOG(“Fish ccTouchEnded”);
/* do your stuff here */
}
CCRect Fish::rect(){
CCRect c = CCRectMake(
sprite->getPosition().x – (sprite->getTextureRect().size.width/2) * sprite->getScaleX(),
sprite->getPosition().y – (sprite->getTextureRect().size.height/2) * sprite->getScaleY(),
sprite->getTextureRect().size.width * sprite->getScaleX() ,
sprite->getTextureRect().size.height * sprite->getScaleY()
);
return c;
}
Link: http://tillawy.wordpress.com/2012/01/07/cocos2d-x-ccnodeccsprite-detect-touch/
I created that Fish object as i saw in tutorial or in many articles.
I have a problem if i create that fish object 6 times, only the 6th one listens the touch events, but if i press other fish it doesnt work. Why can it be happened?
I really need help in that topic
Thank you in advance!