cocos2d-x之计时器(自动计时器和自定义计时器)

cocos2d-x之计时器(自动计时器和自定义计时器)

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     
 9 private:
10     cocos2d::LabelTTF *label;//定义一个label,用于显示移动的图片
11     
12     
13 public:
14     // there's no 'id' in cpp, so we recommend returning the class instance pointer
15     static cocos2d::Scene* createScene();
16 
17     // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
18     virtual bool init();
19 
20     // implement the "static create()" method manually
21     CREATE_FUNC(HelloWorld);
22     
23     //重写update方法(时间的间隔,即两个帧之间的时间间隔),他会在每一帧执行的时候执行一次
24     virtual void update(float dt);
25     
26     //自定义方法,用于改变时间间隔
27     virtual void timerHandler(float dt);
28 };
29 
30 #endif // __HELLOWORLD_SCENE_H__

HelloWorldScene.cpp

 1 #include "HelloWorldScene.h"
 2 #include "cocostudio/CocoStudio.h"
 3 #include "ui/CocosGUI.h"
 4 
 5 USING_NS_CC;
 6 
 7 using namespace cocostudio::timeline;
 8 
 9 Scene* HelloWorld::createScene()
10 {
11     // 'scene' is an autorelease object
12     auto scene = Scene::create();
13     
14     // 'layer' is an autorelease object
15     auto layer = HelloWorld::create();
16 
17     // add layer as a child to scene
18     scene->addChild(layer);
19 
20     // return the scene
21     return scene;
22 }
23 
24 // on "init" you need to initialize your instance
25 bool HelloWorld::init()
26 {
27     //////////////////////////////
28     // 1. super init first
29     if ( !Layer::init() )
30     {
31         return false;
32     }
33     
34     label = LabelTTF::create("bobo", "Courier", 30);
35     addChild(label);
36     
37     
38     //可以设置时间间隔,通过schedule_selector()方法,自动将方法转换成指针类型
39     schedule(schedule_selector(HelloWorld::timerHandler), 1);
40     
41     //无法调整时间间隔
42 //    scheduleUpdate();// 启动update,让其执行移动
43     
44     
45     return true;
46 }
47 
48 //实现自定义的可以改变时间间隔的方法
49 void HelloWorld::timerHandler(float dt){
50     
51     log(">>>>>>>>>>>>>");
52     //设置移动label对象,每一帧向右上角移动(1, 1)
53     label->setPosition(label->getPosition() + Point(10, 10));
54     
55     //停止移动的方法
56     if (label->getPositionX() > 500) {
57         unscheduleUpdate();//停止移动
58     }
59 
60     
61 }
62 
63 
64 //实现update方法,不断的去移动label
65 void HelloWorld::update(float dt){
66     
67     //设置移动label对象,每一帧向右上角移动(1, 1)
68     label->setPosition(label->getPosition() + Point(1, 1));
69     
70     //停止移动的方法
71     if (label->getPositionX() > 500) {
72         unscheduleUpdate();//停止移动
73     }
74     
75 }
原文地址:https://www.cnblogs.com/dudu580231/p/4382531.html