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

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

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

/** * 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 @R_322_4045@ion * 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;
}

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

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...