我正在做一个滑块难题,此功能应先移动磁贴,然后返回主功能,以便我可以继续玩游戏,我也使用此功能在游戏开始时对磁贴进行随机播放,但是当我将其全部调用时这些图块会一起移动并进入错误的位置或移出屏幕,这是因为没有运行 Action moveTo花费0.2秒,然后在0.2秒后返回,它开始 Action 并立即返回,因此在调用此方法时瓷砖仍然在移动,使一切困惑。

有什么方法可以阻止代码在操作完成之前继续执行?谢谢 ;)

bool GameScene::updateTile(Sprite* tile, int newPos)
{
    auto moveTo = MoveTo::create(0.2, Vec2(widthArray[newPos], heightArray[newPos]));
    auto whatever = CallFunc::create([]() {
        CCLOG("hi");
    });
    auto seq = Sequence::create(moveTo, whatever, nullptr);
    tile->runAction(seq);
    CCLOG("running");
    return true;
}

//编辑

此代码打印:
“跑步”
并且在0.2秒后(运行 Action moveTo花费的时间)
“嗨”(无论行动如何)

我的目标是等待0.2秒,然后显示“hi”,并且仅在此之后显示“running”,但是如果我尝试使用任何形式的延迟或循环来停止代码
喜欢:
 bool GameScene::updateTile(Sprite* tile, int newPos)
    {
        auto moveTo = MoveTo::create(0.2, Vec2(widthArray[newPos], heightArray[newPos]));
        auto whatever = CallFunc::create([]() {
            CCLOG("hi");
        });
        auto seq = Sequence::create(moveTo, whatever, nullptr);
        tile->runAction(seq);
        while (tile->getNumberOfRunningActions != 0)
              { //delay
              }
        CCLOG("running");
        return true;
    }

它不会执行任何操作,只会卡住,有什么想法吗?

最佳答案

您可以使用tag检查操作是否完成:

bool GameScene::updateTile(Sprite* tile, int newPos)
{
    static const int MY_MOVE_SEQ = 3333;
    if (tile->getActionByTag(MY_MOVE_SEQ) && !tile->getActionByTag(MY_MOVE_SEQ)->isDone()) {
        return;
        //or you can stop the last action sequence and then run new action
        //tile->stopActionByTag(MY_MOVE_SEQ);
    }

    auto moveTo = MoveTo::create(0.2, Vec2(widthArray[newPos], heightArray[newPos]));
    auto whatever = CallFunc::create([]() {
        CCLOG("hi");
    });
    auto seq = Sequence::create(moveTo, whatever, nullptr);
    //set tag here!
    seq->setTag(MY_MOVE_SEQ);

    tile->runAction(seq);
    CCLOG("running");
    return true;
}

//编辑
    bool anyActionRunning = false;
    tile->getParent()->enumerateChildren("//Tile", [&anyActionRunning](Node* child) {
        if (child->getActionByTag(MY_MOVE_SEQ) && !child->getActionByTag(MY_MOVE_SEQ)->isDone()) {
            anyActionRunning = true;
            return true;
        }
        return false;
    });

// Edit2:
static const string funcName = "CheckAction";
tile->schedule([tile](float dt) {
    if (tile->getNumberOfRunningActions == 0) {
        CCLOG("running");
        tile->unschedule(funcName);
    }
}, funcName);

关于c++ - Cocos2d-x c++-等待操作完成,然后继续,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36045222/

10-09 16:25
查看更多