假设我需要调用一个延迟2秒的函数。在cocos2d-x中,你可以使用actions:
auto action = Sequence::create(
DelayTime::create(2),
CallFunc::create(
[&]() {
// here is the lambda function that does whatever you want after 2 seconds
}
),
NULL
);
runAction(action);
但是为了运行这个动作,你需要一个Node
,它并不总是可用的。有些课程与Node
无关。所以我想知道在c++ 11中添加延迟代码执行的跨平台方式是什么?
看起来这个问题已经结束了,无论如何你可以使用Scheduler来安排你的方法在Cocos2dx中的任何时候被调用。在返回true之前,在类的init方法中执行如下操作:
this->schedule(schedule_selector(HelloWorld::setGamePlaySpeed), .2);
并创建一个方法,将float dt作为参数,像这样…
void HelloWorld::setGamePlaySpeed(float dt){
// do anything yo want... This method will be Called every .2 seconds
}
现在float dt是您在调度程序中指定的dt时间。
你可以使用ussleep函数。
必须包含
#include <unistd.h>
在你的类中,在你需要暂停的地方,你可以像这样放置ussleep函数。
usleep(5000000);
,然后调用你需要运行的函数
这将使你的游戏循环进入5秒睡眠模式。
您可以使用c++ 11线程库中添加的std::this_thread::sleep_for
函数:
std::chrono::seconds duration( 2 );
std::this_thread::sleep_for( duration ); // Sleep for 2 seconds.
这将导致当前线程在duration
对象中指定的持续时间内停止执行。