检测单击了哪个CCSprite

时间:2013-07-22 11:07:41

标签: cocoa-touch cocos2d-x ccsprite cclayer

我的主屏幕是Main.ccbi,它包含3个CCSprite。现在我希望当用户点击CCSprite时我应该知道他点击了哪个? 我想在CCMotionBegin方法中计算出哪个CCSprite用户点击过。

1 个答案:

答案 0 :(得分:2)

首先将您创建的精灵存储在CCArraymSpriteArray,然后您可以执行以下操作

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

希望这有帮助。