您的位置:首页 > 移动开发 > Cocos引擎

Cocos2d-x Schedule定时器的使用实例

2014-09-12 08:47 1336 查看

schedule可以实现定时器的功能,就是每隔一段时间做什么事情,schedule的调用者是节点,所有的节点都可以调用schedule函数,参数需要传入一个函数(schedule_selector一个新的选择器),在函数中可以完成碰撞检测等功能。下面就具体来看看这个函数的用法吧。

bool HelloWorld::init()
{
bool bRet = false;
do
{
CC_BREAK_IF(! CCLayer::init());
//schedule传入一个参数的时候每一帧都会调用show函数
//this->schedule(schedule_selector(HelloWorld::show));
//以下的schedule方法中,传入的第二个参数是时间,代表多长时间调用一次show函数
//this->schedule(schedule_selector(HelloWorld::show),1.0);
//schedule方法中的前俩个参数和上边的相同,第三个参数是方法调用的重复次数,重复俩次加刚开始的一次
//总共调用了三次,3.0代表执行下边的语句后多长时间开始调用函数show,就是delay的时间
//this->schedule(schedule_selector(HelloWorld::show),1.0,2,3.0);
//scheduleUpdate每隔一帧都会调用update方法,需要我们声明一下update方法
this->scheduleUpdate();
bRet = true;
} while (0);
return bRet;
}
void HelloWorld::update(float dt)
{
static int i = 0;
if(i == 100)
{
//下次不再调用update方法,但是CCLog函数还是会执行的。
//this->unscheduleUpdate();
//以下函数实现相同的功能,它会将这个层的所以schedule方法都停止调用
this->unscheduleAllSelectors();
}
CCLog("i = %d",++i);
}
//show函数必须含有一个float类型的参数
void HelloWorld::show(float dt)
{
static int i = 0;
CCLog("time = %d",++i);
if(i == 10)
{
//unschedule停止传入的参数代表的方法调用
//以下代码不一定需要写在这个show方法中
this->unschedule(schedule_selector(HelloWorld::show));
}
}

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息