cocos2d-x游戏循环与调度

每个游戏程序都有一个循环在不断运行,它是有导演对象来管理很维护。若是须要场景中的精灵运动起来,咱们能够在游戏循环中使用定时器(Scheduler)对精灵等对象的运行进行调度。由于Node类封装了Scheduler类,因此咱们也能够直接使用Node中调用函数。

Node中调用函数主要有:html

void scheduleUpdate ( void )。每一个Node对象只要调用该函数,那么这个Node对象就会定时地每帧回调用一次本身的update(float dt)函数。函数

void schedule ( SEL_SCHEDULE selector,  float  interval )。与scheduleUpdate函数功能同样,不一样的是咱们能够指定回调函数(经过selector指定),也能够更加须要指定回调时间间隔。this

void unscheduleUpdate ( void )。中止update(float dt)函数调度。spa

void unschedule ( SEL_SCHEDULE selector )。能够指定具体函数中止调度。.net

void unscheduleAllSelectors ( void )。能够中止调度。code

 

为了进一步了解游戏循环与调度的使用,咱们修改HelloWorld实例。orm

修改HelloWorldScene.h代码,添加update(float dt)声明,代码以下:htm

[html] view plaincopy在CODE上查看代码片派生到个人代码片对象

  1. class HelloWorld : public cocos2d::Layer  blog

  2. {  

  3. public:  

  4.    ... ...  

  5.    

  6.    virtual void update(float dt);  

  7.      

  8.    CREATE_FUNC(HelloWorld);  

  9.    

  10. };  

  11. 修改HelloWorldScene.cpp代码以下:  

  12. bool HelloWorld::init()  

  13. {  

  14.    ... ...  

  15.      

  16.    auto label = LabelTTF::create("Hello World","Arial", 24);  

  17.    label->setTag(123);                                                                                                                       ①  

  18.    ... ...  

  19.    

  20.    //更新函数   

  21.    this->scheduleUpdate();                                                                                                              ②  

  22.    //this->schedule(schedule_selector(HelloWorld::update),1.0f/60);                                              ③  

  23.      

  24.    return true;  

  25. }  

  26.    

  27. voidHelloWorld::update(float dt)                                                                                                      ④  

  28. {      

  29.     auto label =this->getChildByTag(123);                                                                                  ⑤       

  30.     label->setPosition(label->getPosition()+ Point(2,-2));                                                                   ⑥  

  31. }   

  32.    

  33. void HelloWorld::menuCloseCallback(Ref*pSender)  

  34. {  

  35.     //中止更新   

  36.    unscheduleUpdate();                                                                                                           ⑦  

  37.    Director::getInstance()->end();  

  38.    

  39. #if (CC_TARGET_PLATFORM ==CC_PLATFORM_IOS)  

  40.    exit(0);  

  41. #endif  

  42. }  


为了可以在init函数以外访问标签对象label,咱们须要为标签对象设置Tag属性,其中的第①行代码就是设置Tag属性为123。第⑤行代码是经过Tag属性得到从新得到这个标签对象。

为了可以开始调度还须要在init函数中调用scheduleUpdate(见第②行代码)或schedule(见第③行代码)。

代码第④行的HelloWorld::update(floatdt)函数是在调度函数,精灵等对象的变化逻辑都是在这个函数中编写的。咱们这个例子很简单只是让标签对象动起来,第⑥行代码就是改变它的位置。

为了省电等目的,若是再也不使用调度,必定不要忘记中止调度。第⑦行代码unscheduleUpdate()就是中止调度update,若是是其余的调度函数能够采用unschedule或unscheduleAllSelectors中止。

相关文章
相关标签/搜索