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

时间:2022-11-10 16:45:07
 #ifndef _DRAGLABEL_H_
#define _DRAGLABEL_H_ #include "cocos2d.h"
USING_NS_CC; class DragLabel : public Layer {
private:
Node* pickNode = NULL;
Point delta;
LabelTTF * lbl;
public:
/*得到 Scene 的静态方法,在AppDelegate类中需要使用*/
static Scene* getScene() {
auto sc = Scene::create();
sc->addChild(DragLabel::create());
return sc;
} /*实现init方法,并在一开始需要先调用父类 Layer 的init方法初始化父类*/
virtual bool init() {
if (!Layer::init()) {
return false;
}
// 得到窗口的大小
auto size = Director::getInstance()->getWinSize();
// Label
lbl = LabelTTF::create("I am a Label", "Arial", );
lbl->setPosition(Point(size.width / , size.height - )); this->addChild(lbl, , ); // 注册 触摸事件
this->setTouchEnabled(true); // 注册 Update 事件 : 需要实现 Node 类的 虚函数 void update(float delta)
this->scheduleUpdate(); // 注册一个 固定时间调用的事件 可以指定 间隔时间 (注意调用的方式与普通的
// Callback 不同 : schedule_selector(DragLabel::downLabel) , 方法要写类名
this->schedule(schedule_selector(DragLabel::downLabel), 1.0f); return true;
} // FixedUpdate CallBack Function
void downLabel(float delta) {
lbl->setPositionY(lbl->getPositionY() - );
} // Update Function
virtual void update(float delta) {
lbl->setPositionX(lbl->getPositionX() + 60.0 / );
} // Events
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event) {
if (touches.size() == ) {
Object* tmp = NULL;
Point p = touches[]->getLocation();
CCARRAY_FOREACH(this->getChildren(), tmp) {
Node* node = (Node*)tmp;
if (node->getBoundingBox().containsPoint(p)) {
pickNode = node;
delta = p - node->getPosition();
break;
}
}
}
}
virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *unused_event) {
if (pickNode) {
pickNode->setPosition(touches[]->getLocation() - delta);
}
}
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *unused_event) {
pickNode = nullptr;
} /*这个宏就是帮助我们实现那个 XXX::create() 方法*/
CREATE_FUNC(DragLabel);
}; #endif