/* 动作监听...写一个小玩意,怪物归家,哈哈哈 */
// 创建一所小房子
auto home = Sprite::create("res/home.png");
home->setPosition(Point(400,400));
this->addChild(home);
// 创建一个怪物
auto guaiwu = Sprite::create("res/tk.png");
guaiwu->setPosition(Point(200,200));
this->addChild(guaiwu);
// 创建一个移动动作,将重点设为房子的位置,走过去的过程需要10秒
auto moveTo = MoveBy::create(10.0f, Point(200,200));
// 创建回调函数
auto callFunction = [&](){
CCLOG("到家啦~");
auto label1 = Label::createWithTTF("Back home success!", "fonts/Marker Felt.ttf", 24);
label1->setPosition(Point(100,100));
this->addChild(label1);
};
// 注册回调函数
auto callFun = CallFunc::create(callFunction);
// 将动作和回调函数进行合并,当动作执行完执行函数
auto actions = Sequence::create(moveTo,callFun, NULL);
// 开始走啦~~
guaiwu->runAction(actions);
用lambda方式精简回调函数代码
// 创建一所小房子
auto home = Sprite::create("res/home.png");
home->setPosition(Point(400,400));
this->addChild(home);
// 创建一个怪物
auto guaiwu = Sprite::create("res/tk.png");
guaiwu->setPosition(Point(200,200));
this->addChild(guaiwu);
// 创建一个移动动作,将重点设为房子的位置,走过去的过程需要10秒
auto moveTo = MoveBy::create(10.0f, Point(200,200));
// 回调函数
auto callFun = CallFunc::create([&](){
CCLOG("到家啦~");
auto label1 = Label::createWithTTF("Back home success!", "fonts/Marker Felt.ttf", 24);
label1->setPosition(Point(100,100));
this->addChild(label1);
});
// 将动作和回调函数进行合并,当动作执行完执行函数
auto actions = Sequence::create(moveTo,callFun, NULL);
// 开始走啦~~
guaiwu->runAction(actions);