cocoa-touchcocos2d-xccspritecclayer

Detecting on which CCSprite has been clicked


My main screen is Main.ccbi, it contains 3 CCSprite. Now I want that when user clicks on a CCSprite I should know on which he has clicked? I want to calculate in CCMotionBegin method that on which CCSprite user has clicked.


Solution

  • First store the sprites you have created in a CCArray say mSpriteArray and then you can do something like the following

    bool MyClass :: ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
    {
        CCPoint currentTouchLocation = pTouch->getLocationInView();
        currentTouchLocation = CCDirector::sharedDirector()->convertToGL(currentTouchLocation);
        currentTouchLocation = this->convertToNodeSpace(currentTouchLocation);
    
        CCSprite *selectedSprite = getSpriteAtPosition(currentTouchLocation);
    
        return true;
    }
    
    CCSprite* MyClass :: getSpriteAtPosition(CCPoint inTouchPosition)
    {
        CCObject *object;
        CCARRAY_FOREACH(mSpriteArray, object)
        {
            CCSprite *sprite = (CCSprite*)sprite;
    
            if (sprite->boundingBox().containsPoint(inTouchPosition))
            {
                return sprite;
            }
        }
    
        return NULL;
    }
    

    Hope this helps.