控制层的任务就是监听触摸事件,然后回调代理方法。控制层并不具体处理任务事情,只是抛给代理处理,因此需要先设计一个代理。
代理只是一个方法,那就是触摸:
/** * 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;
}
好了,下一步该说说状态层了
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。