首页 > 代码库 > cocos2d-x-3.x bringToFront & sendToBack实现

cocos2d-x-3.x bringToFront & sendToBack实现

void Node::bringToFront(void)
{
    auto parent = this->getParent();
    if (parent != nullptr && parent->getChildrenCount() >= 2) {

        auto& siblings = parent->getChildren();

        auto last = *siblings.rbegin();
        auto topOrderOfArrival = last->getOrderOfArrival();
        auto topLocalZOrder = last->getLocalZOrder();

        for (size_t idx = siblings.size() - 1; idx > 0; --idx)
        {
            auto sibling = siblings.at(idx);
            if (sibling != this) {
                sibling->setOrderOfArrival(siblings.at(idx - 1)->getOrderOfArrival());
                sibling->_setLocalZOrder(siblings.at(idx - 1)->getLocalZOrder());
            }
            else {
                break;
            }
        }

        this->setOrderOfArrival(topOrderOfArrival);
        this->_setLocalZOrder(topLocalZOrder);

        std::sort(std::begin(siblings), std::end(siblings), nodeComparisonLess);
        _eventDispatcher->setDirtyForNode(this);
    }
}

void Node::sendToBack(void)
{
    auto parent = this->getParent();
    if (parent != nullptr && parent->getChildrenCount() >= 2) {

        auto& siblings = parent->getChildren();
        auto start = *siblings.begin();
        auto bottomOrderOfArrival = start->getOrderOfArrival();
        auto bottomLocalZOrder = start->getLocalZOrder();
        
        for (size_t idx = 0; idx < siblings.size() - 1; ++idx)
        {
            auto c = siblings.at(idx);
            if (c != this) {
                c->setOrderOfArrival(siblings.at(idx + 1)->getOrderOfArrival());
                c->_setLocalZOrder(siblings.at(idx + 1)->getLocalZOrder());
            }
            else {
                break;
            }
        }

        this->setOrderOfArrival(bottomOrderOfArrival);
        this->_setLocalZOrder(bottomLocalZOrder);

        std::sort(std::begin(siblings), std::end(siblings), nodeComparisonLess);
        _eventDispatcher->setDirtyForNode(this);
    }
}

cocos2d-x-3.x bringToFront & sendToBack实现