cocos2d-x 真正的定時器之schedule

在遊戲設計時,咱們須要不斷的改變屏幕顯示來反映遊戲操做的效果,最簡單的就是提示用戶已經進行的遊戲時間。爲此,咱們須要使用cocos2d-x內置的任務調度機制,即CCNode的schedule成員函數。  java

void  schedule (SEL_SCHEDULE selector)
  schedules a selector. 
void  schedule (SEL_SCHEDULE selector, ccTime interval)
  schedules a custom selector with an interval time in seconds. 
void  unschedule (SEL_SCHEDULE selector)
  unschedules a custom selector. 
void  unscheduleAllSelectors (void)
  unschedule all scheduled selectors: custom selectors, and the 'update' selector. 
cocos2d-x中的schedule有兩種做用:

1)定時執行方法
 例如,每隔1秒就執行GameLayer類的方法step(ccTime dt)。

this->schedule(schedule_selector(GameLayer::step), 1.0f);
...
void GameLayer::step(ccTime dt)
{
...
}
2)延時執行方法
 例如, 延時 5秒執行GameLayer類的方法step(ccTime dt)。

this->schedule(schedule_selector(GameLayer::step), 5.0f);
...
void GameLayer::step(ccTime dt)
{
this-> unschedule(schedule_selector( GameLayer::step  )); // 去除定時器, 這樣該方法也就執行一次
...
}


1. 不調用update函數,調用本身的函數 函數

其實原理是同樣的,咱們調用scheduleUpdate的時候,系統默認每幀去調用update函數,但若是咱們想調用本身的函數呢?很簡單,先給HelloWorldScene添加一個函數: this

[cpp]  view plain copy print ?
 
  1. private:  
  2.     /* 自定義的update函數 */  
  3.     void MutUpdate(float fDelta);  


 

一樣在函數裏打日誌: spa

[cpp]  view plain copy print ?
 
  1. void HelloWorld::MutUpdate( float fDelta )  
  2. {  
  3.     CCLOG("MutUpdate");  
  4. }  


 

而後咱們要添加一句很暴力的代碼: 設計

[cpp]  view plain copy print ?
 
  1. bool HelloWorld::init()  
  2. {  
  3.     bool bRet = false;  
  4.     do   
  5.     {  
  6.         CC_BREAK_IF(! CCLayer::init());  
  7.   
  8.         //this->scheduleUpdate();  
  9.   
  10.         /* 指定每幀執行自定義的函數 */  
  11.         this->schedule(schedule_selector(HelloWorld::MutUpdate));  
  12.         bRet = true;  
  13.     } while (0);  
  14.   
  15.     return bRet;  
  16. }  


 

咱們使用schedule指定了一個自定義的函數,而後咱們用調試模式運行項目,將看到如下輸出: 調試

MutUpdate 日誌

MutUpdate orm

MutUpdate 遊戲

MutUpdate 回調函數

MutUpdate

MutUpdate

MutUpdate

MutUpdate

我想,沒有什麼能夠解釋的,就是指定了一個回調函數。

(小若:其實他不懂。)

 

2. 真正的定時

好喇,咱們要真正建立一個定時器了,咱們修改一下schedule的參數就能夠了:

[java]  view plain copy print ?
 
  1. this->schedule(schedule_selector(HelloWorld::MutUpdate), 1.0f);  


 

第二個參數的意思是,每隔多少秒執行一次MutUpdate函數,記住,單位是秒。

相關文章
相關標籤/搜索