cocos2d-x-3.x 工具(1)计时器
这个就是设置一个函数,每隔多少帧或者多少时间执行一下。
首先设置头文件HelloWorldScene.h
1 #ifndef __HELLOWORLD_SCENE_H__ 2 #define __HELLOWORLD_SCENE_H__ 3 4 #include "cocos2d.h" 5 6 class HelloWorld : public cocos2d::Layer 7 { 8 private: 9 cocos2d::LabelTTF *label; 10 public: 11 // there's no 'id' in cpp, so we recommend returning the class instance pointer 12 static cocos2d::Scene* createScene(); 13 14 // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone 15 virtual bool init(); 16 17 // a selector callback 18 void menuCloseCallback(cocos2d::Ref* pSender); 19 20 // implement the "static create()" method manually 21 CREATE_FUNC(HelloWorld); 22 virtual void update(float dt);//函数,帧之间时间间隔 23 void timerHandler(float dt);//自写函数,计时函数 24 }; 25 #endif // __HELLOWORLD_SCENE_H__
标记出来的就是要声明的两个函数,第一个是以帧为单位执行,第二个是以时间为单位执行。
然后修改cpp文件
1 bool HelloWorld::init() 2 { 3 if ( !Layer::init()) 4 { 5 return false; 6 } 7 Size size = Director::getInstance()->getVisibleSize(); //获取有效长度 8 9 label = LabelTTF::create("fuck", "Courier", 30);//设置移动目标 10 addChild(label);//添加到图层 11 //schedule(schedule_selector(HelloWorld::timerHandler), 1);//设置,每隔一秒执行一次 12 scheduleUpdate();//启动函数 13 return true; 14 } 15 /*void HelloWorld::timerHandler(float dt){//实现此函数,计时函数 16 log(">>"); 17 }*/ 18 void HelloWorld::update(float dt){//实现update方法 19 label->setPosition(label->getPosition() + Point(1, 1)); 20 if (label->getPositionX()>300){//加入判断当X>300时 21 unscheduleUpdate();//停止函数 22 } 23 }
注释掉的两个为计时执行功能,现在的状态为按帧数执行。
如果要执行计时功能,注释update函数以及启动函数,取消timerHandler函数以及设置的注释。