cocos2d-x 3.0 学习笔记: 一个可以拖拽的Label及schedule的应用

 1 #ifndef _DRAGLABEL_H_
 2 #define _DRAGLABEL_H_
 3 
 4 #include "cocos2d.h"
 5 USING_NS_CC;
 6 
 7 class DragLabel : public Layer {
 8 private:
 9     Node* pickNode = NULL;
10     Point delta;
11     LabelTTF * lbl;
12 public:
13     /*得到 Scene 的静态方法,在AppDelegate类中需要使用*/
14     static Scene* getScene() {
15         auto sc = Scene::create();
16         sc->addChild(DragLabel::create());
17         return sc;
18     }
19 
20     /*实现init方法,并在一开始需要先调用父类 Layer 的init方法初始化父类*/
21     virtual bool init() {
22         if (!Layer::init()) {
23             return false;
24         }
25         // 得到窗口的大小
26         auto size = Director::getInstance()->getWinSize();
27         // Label
28         lbl = LabelTTF::create("I am a Label", "Arial", 18);
29         lbl->setPosition(Point(size.width / 2, size.height - 30));
30 
31         this->addChild(lbl, 1, 100);
32 
33         // 注册 触摸事件
34         this->setTouchEnabled(true);
35 
36         // 注册 Update 事件 : 需要实现 Node 类的 虚函数 void update(float delta)
37         this->scheduleUpdate();
38 
39         // 注册一个 固定时间调用的事件 可以指定 间隔时间 (注意调用的方式与普通的
40         // Callback 不同 : schedule_selector(DragLabel::downLabel) , 方法要写类名
41         this->schedule(schedule_selector(DragLabel::downLabel), 1.0f);
42 
43         return true;
44     }
45 
46     // FixedUpdate CallBack Function
47     void downLabel(float delta) {
48         lbl->setPositionY(lbl->getPositionY() - 5);
49     }
50 
51     // Update Function
52     virtual void update(float delta) {
53         lbl->setPositionX(lbl->getPositionX() + 60.0 / 60);
54     }
55 
56     // Events
57     virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event) {
58         if (touches.size() == 1) {
59             Object* tmp = NULL;
60             Point p = touches[0]->getLocation();
61             CCARRAY_FOREACH(this->getChildren(), tmp) {
62                 Node* node = (Node*)tmp;
63                 if (node->getBoundingBox().containsPoint(p)) {
64                     pickNode = node;
65                     delta = p - node->getPosition();
66                     break;
67                 }
68             }
69         }
70     }
71     virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *unused_event) {
72         if (pickNode) {
73             pickNode->setPosition(touches[0]->getLocation() - delta);
74         }
75     }
76     virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *unused_event) {
77         pickNode = nullptr;
78     }
79 
80     /*这个宏就是帮助我们实现那个 XXX::create() 方法*/
81     CREATE_FUNC(DragLabel);
82 };
83 
84 #endif

 

posted @ 2013-12-26 23:14  easyfrog  阅读(532)  评论(0编辑  收藏  举报