Cocos2d动作: 动作监听

来源:互联网 发布:炫浪网络社区 - 电脑版 编辑:程序博客网 时间:2024/04/27 18:12
  1.     /* 动作监听...写一个小玩意,怪物归家,哈哈哈 */
  2.    // 创建一所小房子
  3.    auto home = Sprite::create("res/home.png");
  4.    home->setPosition(Point(400,400));
  5.    this->addChild(home);
  6.  
  7.    // 创建一个怪物
  8.    auto guaiwu = Sprite::create("res/tk.png");
  9.    guaiwu->setPosition(Point(200,200));
  10.    this->addChild(guaiwu);
  11.    // 创建一个移动动作,将重点设为房子的位置,走过去的过程需要10秒
  12.    auto moveTo = MoveBy::create(10.0f, Point(200,200));
  13.    
  14.    // 创建回调函数
  15.    auto callFunction = [&](){
  16.  
  17.        CCLOG("到家啦~");
  18.        
  19.        auto label1 = Label::createWithTTF("Back home success!", "fonts/Marker Felt.ttf", 24);
  20.    
  21.        label1->setPosition(Point(100,100));
  22.        
  23.        this->addChild(label1);
  24.    };
  25.    
  26.    // 注册回调函数
  27.    auto callFun = CallFunc::create(callFunction);
  28.    
  29.    // 将动作和回调函数进行合并,当动作执行完执行函数
  30.    auto actions = Sequence::create(moveTo,callFun, NULL);
  31.    
  32.    // 开始走啦~~
  33.    guaiwu->runAction(actions);


用lambda方式精简回调函数代码

  1.    // 创建一所小房子
  2.    auto home = Sprite::create("res/home.png");
  3.    home->setPosition(Point(400,400));
  4.    this->addChild(home);
  5.  
  6.    // 创建一个怪物
  7.    auto guaiwu = Sprite::create("res/tk.png");
  8.    guaiwu->setPosition(Point(200,200));
  9.    this->addChild(guaiwu);
  10.    // 创建一个移动动作,将重点设为房子的位置,走过去的过程需要10秒
  11.    auto moveTo = MoveBy::create(10.0f, Point(200,200));
  12.   // 回调函数
  13.    auto callFun = CallFunc::create([&](){
  14.    
  15.        CCLOG("到家啦~");
  16.        
  17.        auto label1 = Label::createWithTTF("Back home success!", "fonts/Marker Felt.ttf", 24);
  18.        
  19.        label1->setPosition(Point(100,100));
  20.        
  21.        this->addChild(label1);
  22.    
  23.    });
  24.    
  25.    // 将动作和回调函数进行合并,当动作执行完执行函数
  26.    auto actions = Sequence::create(moveTo,callFun, NULL);
  27.    
  28.    // 开始走啦~~
  29.    guaiwu->runAction(actions);
  30.    








0 0
原创粉丝点击