原创文章,转载请注明出处:http://blog.csdn.net/zhy_cheng/article/details/8274042
使用CCNode的schedule函数可以实现一个定时器,该函数一共有三个重载的函数
- void
CCNode::unscheduleUpdate() - {
-
m_pScheduler->unscheduleUpdateForTarge t(this); - }
-
- void
CCNode::schedule(SEL_SCHEDULE selector) - {
-
this->schedule(selector, 0.0f, kCCRepeatForever, 0.0f); - }
-
- void
CCNode::schedule(SEL_SCHEDULE selector, float interval) - {
-
this->schedule(selector, interval, kCCRepeatForever, 0.0f); - }
-
- void
CCNode::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay) - {
-
CCAssert( selector, "Argument must be non-nil"); -
CCAssert( interval >=0, "Argument must be positive"); -
-
m_pScheduler->scheduleSelector(selector, this, interval, !m_bIsRunning, repeat, delay); - }
-
- void
CCNode::scheduleOnce(SEL_SCHEDULE selector, float delay) - {
-
this->schedule(selector, 0.0f, 0, delay); - }
-
- void
CCNode::unschedule(SEL_SCHEDULE selector) - {
-
// explicit nil handling -
if (selector == 0) -
return; -
-
m_pScheduler->unscheduleSelector(selector, this); - }
-
- void
CCNode::unscheduleAllSelectors() - {
-
m_pScheduler->unscheduleAllSelectorsFo rTarget(this); - }
-
- void
CCNode::resumeSchedulerAndAction s() - {
-
m_pScheduler->resumeTarget(this); -
m_pActionManager->resumeTarget(this); - }
-
- void
CCNode::pauseSchedulerAndActions () - {
-
m_pScheduler->pauseTarget(this); -
m_pActionManager->pauseTarget(this); - }
上面的代码是CCNode类中与schedule的代码。
void CCNode::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay)
第一个参数是回调函数的指针
第二个参数是间隔多少时间调用一次
第三个参数是调用这个函数多少次
第四个参数是多少时间后调用这个函数
void CCNode::schedule(SEL_SCHEDULE selector)
默认每帧调用一次,调用无数次,马上调用
void CCNode::schedule(SEL_SCHEDULE selector, float interval)
调用无数次,马上调用。
有了定时器,我们就可以让某个函数一直执行下去,也可以然函数延时执行,也可以让函数执行若干次。
可以在init函数中调用这个方法,也可以在onEnter函数中调用这个方法,注意了,在onEnter函数中个调用这个方法的话,要保证调用父类的onEnter方法。
onEnter函数可能被多次调用,但是init是初始化的时候调用。
回调函数没有返回值,有一个float参数,表示距离上次调用该方法的时间长度。
- void
HelloWorld::update(float dt) - {
-
-
char *buf=new char[50]; -
-
memset(buf,0,10); -
sprintf(buf,"dt=%f",dt); -
CCLog(buf); -
-
delete []buf;