我正在制作一个 slider 拼图,这个函数应该移动一个方 block 然后返回到主函数以便我可以继续玩,我也在游戏开始时使用这个函数来洗牌但是当我称之为所有的瓷砖一起移动并进入错误的位置或离开屏幕,这是因为而不是运行需要 0.2 秒的 Action moveTo 然后在 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 所需的时间) “嗨”(来自任何 Action )
我的目标是让它等待 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;
}
它没有执行任何操作,只是卡住了,有什么想法吗?
最佳答案
您可以使用标签
来检查一个 Action 是否已经完成:
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;
});
//编辑2:
static const string funcName = "CheckAction";
tile->schedule([tile](float dt) {
if (tile->getNumberOfRunningActions == 0) {
CCLOG("running");
tile->unschedule(funcName);
}
}, funcName);
关于c++ - Cocos2d-x c++ - 在继续之前等待 Action 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36045222/