原創文章,轉載請註明出處:http://blog.csdn.net/zhy_cheng/article/details/8274042
使用CCNode的schedule函數可以實現一個定時器,該函數一共有三個重載的函數
void CCNode::unscheduleUpdate(){ m_pScheduler->unscheduleUpdateForTarget(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->unscheduleAllSelectorsForTarget(this);}void CCNode::resumeSchedulerAndActions(){ 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;}