加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2dx3.3开发FlappyBird总结十一:控制层功能设计

发布时间:2020-12-14 20:38:46 所属栏目:百科 来源:网络整理
导读:控制层的任务就是监听触摸事件,然后回调代理方法。控制层并不具体处理任务事情,只是抛给代理处理,因此需要先设计一个代理。 代理只是一个方法,那就是触摸: /** * The delegate between option layer and game layer */ class OptionDelegate { public:

控制层的任务就是监听触摸事件,然后回调代理方法。控制层并不具体处理任务事情,只是抛给代理处理,因此需要先设计一个代理。

代理只是一个方法,那就是触摸:

/** * The delegate between option layer and game layer */
class OptionDelegate {
public:
  /** * When touch the option layer,it will be called */
  virtual void onTouch() = 0;
};

代理类被声明为纯虚函数,这样自己是不能实现的,且遵守此代理的类,必须要实现此代理中的方法。

下面说说控制层:

class OptionDelegate;

/** * The game background,showing the background information * in the game. */
class OptionLayer : public cocos2d::Layer {
public:
  /**
   * The default constructor
   */
  OptionLayer();

  /** * The default destructor */
  ~OptionLayer();

  /** * The init method,will init the super init method first * * @return true if succeeded,otherwise false */
  virtual bool init();

  CREATE_FUNC(OptionLayer);

  /** * Override the multitouch method */
  virtual void onTouchesBegan(const std::vector<cocos2d::Touch*>& touches,cocos2d::Event *unused_event);

  /** * The delegate */
  CC_SYNTHESIZE(OptionDelegate*,_optionDelegate,OptionDelegate);
};

看到CC_SYNTHESIZE(OptionDelegate*,OptionDelegate);这行了吗,这是设置代理,如果阅读不懂什么是代理,那先去找相关文章阅读。如果读者做过IOS开发,那么一定很熟悉,因为那是最常用的通信机制。

简单来说,这里控制层监听触摸事件,然后控制层就告诉代理,我监听到触摸事件了,那么代理实现对应的方法,就可以了。

在初始化时,让控制层添加监听事件:

bool OptionLayer::init() {
  if (!Layer::init()) {
    return false;
  }

  // Register touches began event
  auto listener = EventListenerTouchAllAtOnce::create();
  listener->onTouchesBegan = CC_CALLBACK_2(OptionLayer::onTouchesBegan,this);

// // 这个是3.0后的新特性,这里就没有使用,主要还是想先了解旧方式,但新的方式也是需要知道的
// listener->onTouchesBegan = [&](const std::vector<Touch *> &touches,Event *event) {
// CCLOG("touches begin");
// if (this->getOptionDelegate()) {
// this->getOptionDelegate()->onTouch();
// }
// };
  auto dispatcher = Director::getInstance()->getEventDispatcher();
  dispatcher->addEventListenerWithSceneGraphPriority(listener,this);

  return true;
}

好了,下一步该说说状态层了

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读