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

前端之家收集整理的这篇文章主要介绍了cocos2dx3.3开发FlappyBird总结十一:控制层功能设计前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

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

下面说说控制层:

  1. class OptionDelegate;
  2.  
  3. /** * The game background,showing the background information * in the game. */
  4. class OptionLayer : public cocos2d::Layer {
  5. public:
  6. /**
  7. * The default constructor
  8. */
  9. OptionLayer();
  10.  
  11. /** * The default destructor */
  12. ~OptionLayer();
  13.  
  14. /** * The init method,will init the super init method first * * @return true if succeeded,otherwise false */
  15. virtual bool init();
  16.  
  17. CREATE_FUNC(OptionLayer);
  18.  
  19. /** * Override the multitouch method */
  20. virtual void onTouchesBegan(const std::vector<cocos2d::Touch*>& touches,cocos2d::Event *unused_event);
  21.  
  22. /** * The delegate */
  23. CC_SYNTHESIZE(OptionDelegate*,_optionDelegate,OptionDelegate);
  24. };

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

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

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

  1. bool OptionLayer::init() {
  2. if (!Layer::init()) {
  3. return false;
  4. }
  5.  
  6. // Register touches began event
  7. auto listener = EventListenerTouchAllAtOnce::create();
  8. listener->onTouchesBegan = CC_CALLBACK_2(OptionLayer::onTouchesBegan,this);
  9.  
  10. // // 这个是3.0后的新特性,这里就没有使用,主要还是想先了解旧方式,但新的方式也是需要知道的
  11. // listener->onTouchesBegan = [&](const std::vector<Touch *> &touches,Event *event) {
  12. // CCLOG("touches begin");
  13. // if (this->getOptionDelegate()) {
  14. // this->getOptionDelegate()->onTouch();
  15. // }
  16. // };
  17. auto dispatcher = Director::getInstance()->getEventDispatcher();
  18. dispatcher->addEventListenerWithSceneGraPHPriority(listener,this);
  19.  
  20. return true;
  21. }

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

猜你在找的Cocos2d-x相关文章