cocos2d. How to create a popup modal dialog (with

2019-05-26 08:15发布

问题:

I need to make a modal dialog(inherited from CCLayer) that is showing in the center of the main layer. While it is showing, you can not press any other button outside the dialog. Just like a normal modal window in MS Windows System.

The problem is that I can not figure out how to disable the mainlayer's touch events while the dialog is showing.

Any help would be aprreciated.

回答1:

Just set

self.isTouchEnabled = NO;

in the main layer while the popup is displayed. Then later set it back to YES.



回答2:

This works for me in Cocos2d-x but can be adapted to Cocos2d too.

I've change setParent to:

virtual void setParent(CCNode* parent)
{
    CCLayerColor::setParent(parent);        

    if (parent)
    {
        saveTouchesRecursive(parent);

        for (unsigned int i=0; i<mSavedTouches.size(); i++)
        {
            CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(mSavedTouches[i]);
        }
    }
    else
    {
        for (unsigned int i=0; i<mSavedTouches.size(); i++)
        {
            CCStandardTouchDelegate* standardTouchDelegate =  dynamic_cast<CCStandardTouchDelegate*>(mSavedTouches[i]);
            CCTargetedTouchDelegate* targetedTouchDelegate =  dynamic_cast<CCTargetedTouchDelegate*>(mSavedTouches[i]);

            CCLayer* layer =  dynamic_cast<CCLayer*>(mSavedTouches[i]);

            if (layer)
            {
                layer->registerWithTouchDispatcher();
            }
            else if (standardTouchDelegate)
            {
                CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(mSavedTouches[i], 0);
            }
            else if (targetedTouchDelegate)
            {
                CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(mSavedTouches[i], 0,  false);
            }
            else
            {
                CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(mSavedTouches[i], 0,  false);
            }
        }
    }
}

And added the following recursive code to save the touch delegates so I can restore them when the dialog dismissed:

std::vector<CCTouchDelegate*> mSavedTouches;
void saveTouchesRecursive(CCNode* node)
{
    if (node != this)
    {    
        CCTouchDelegate* touchDelegate = dynamic_cast<CCTouchDelegate*>(node);
        if (touchDelegate)
        {
            CCTouchHandler* handler = CCDirector::sharedDirector()->getTouchDispatcher()->findHandler(touchDelegate);

            if (handler)
            {
                mSavedTouches.push_back(touchDelegate);
             }
        }

        for (unsigned int i=0; i<node->getChildrenCount(); i++)
        {
            CCNode* childNode = dynamic_cast<CCNode*>(node->getChildren()->objectAtIndex(i));

            if (childNode)
            {
                saveTouchesRecursive(childNode);
            }
        } 
    }
}