cocos2d-x遊戲循環與調度
每一個遊戲程序都有一個循環在不斷運行它是有導演對象來管理很維護。如果需要場景中的精靈運動起來我們可以在遊戲循環中使用定時器Scheduler對精靈等對象的運行進行調度。因為Node類封裝了Scheduler類所以我們也可以直接使用Node中調用函數。
Node中調用函數主要有
void scheduleUpdate ( void )。每個Node對象隻要調用該函數那麼這個Node對象就會定時地每幀回調用一次自己的update(float dt)函數。
void schedule ( SEL_SCHEDULE selector, float interval )。與scheduleUpdate函數功能一樣不同的是我們可以指定回調函數通過selector指定也可以更加需要指定回調時間間隔。
void unscheduleUpdate ( void )。停止update(float dt)函數調度。
void unschedule ( SEL_SCHEDULE selector )。可以指定具體函數停止調度。
void unscheduleAllSelectors ( void )。可以停止調度。
為了進一步了解遊戲循環與調度的使用我們修改HelloWorld實例。
修改HelloWorldScene.h代碼添加update(float dt)聲明代碼如下
class HelloWorld : public cocos2d::Layer { public: ... ... virtual void update(float dt); CREATE_FUNC(HelloWorld); }; 修改HelloWorldScene.cpp代碼如下 bool HelloWorld::init() { ... ... auto label = LabelTTF::create("Hello World","Arial", 24); label->setTag(123); ① ... ... //更新函數 this->scheduleUpdate(); ② //this->schedule(schedule_selector(HelloWorld::update),1.0f/60); ③ return true; } voidHelloWorld::update(float dt) ④ { auto label =this->getChildByTag(123); ⑤ label->setPosition(label->getPosition()+ Point(2,-2)); ⑥ } void HelloWorld::menuCloseCallback(Ref*pSender) { //停止更新 unscheduleUpdate(); ⑦ Director::getInstance()->end(); #if (CC_TARGET_PLATFORM ==CC_PLATFORM_IOS) exit(0); #endif }
為了能夠在init函數之外訪問標簽對象label我們需要為標簽對象設置Tag屬性其中的第①行代碼就是設置Tag屬性為123。第⑤行代碼是通過Tag屬性獲得重新獲得這個標簽對象。
為了能夠開始調度還需要在init函數中調用scheduleUpdate見第②行代碼或schedule見第③行代碼。
代碼第④行的HelloWorld::update(floatdt)函數是在調度函數精靈等對象的變化邏輯都是在這個函數中編寫的。我們這個例子很簡單隻是讓標簽對象動起來第⑥行代碼就是改變它的位置。
為了省電等目的如果不再使用調度一定不要忘記停止調度。第⑦行代碼unscheduleUpdate()就是停止調度update如果是其他的調度函數可以采用unschedule或unscheduleAllSelectors停止。
《Cocos2d-x實戰 C++卷》現已上線各大商店均已開售
京東https://item.jd.com/11584534.html
當當https://product.dangdang.com/23606265.html
互動出版網https://product.china-pub.com/3770734
《Cocos2d-x實戰 C++卷》源碼及樣章下載地址
源碼下載地址https://51work6.com/forum.php?mod=viewthread&tid=1155&extra=page%3D1
樣章下載地址https://51work6.com/forum.php?mod=viewthread&tid=1157&extra=page%3D1

最後更新:2017-04-03 12:56:32