最近在用cocos studio搞了好几天没有好方法处理回调函数的问题,在论坛里面有教程说用自定义类来设置配合回调特性可以解决(不过我最终还是没有成功过)
最近发现有种简单的代码方式可以实现回调,写出来给初学者参考。
环境版本,我的例子是cocos2d-x v3.5 frameworks + cocos studio v2.2.1 + win7
新建一完成的cocos studio工程,添加 Slider、Button、LoadingBar等组件(注意记录好它们的逻辑标签)
以上的工作后续应该分配给UI完成
以下是程序员要做的
用代码工具(我这里是用vs2012),修改HelloWorldScene.h、HelloWorldScene.cpp的代码,修改的部分很少各位自己看看就明白
//---------------------HelloWorldScene.h--------------------------------------------------
#ifndef HELLOWORLD_SCENE_H
#define HELLOWORLD_SCENE_H
#include “cocos2d.h”
#include “cocostudio/CocoStudio.h”
#include “ui/CocosGUI.h”
class HelloWorld : public cocos2d::Layer
{
public:
// there’s no ‘id’ in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
void uiBtnClickCallback(Ref * pSender);
void uiSliderCallback(Ref * pSender,cocos2d::ui::Slider::EventType evType);
};
#endif // HELLOWORLD_SCENE_H
//---------------------HelloWorldScene.cpp--------------------------------------------------
#include “HelloWorldScene.h”
USING_NS_CC;
using namespace cocostudio::timeline;
Scene* HelloWorld::createScene()
{
// ‘scene’ is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on “init” you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
auto rootNode = CSLoader::createNode("MainScene.csb");
addChild(rootNode);
cocos2d::ui::Button * uilistbtn = (cocos2d::ui::Button *)rootNode->getChildByTag(11);
uilistbtn->addClickEventListener(CC_CALLBACK_1(HelloWorld::uiBtnClickCallback,this));
cocos2d::ui::Slider * m_uiSlider = (cocos2d::ui::Slider *)rootNode->getChildByTag(9);
m_uiSlider->addEventListener(CC_CALLBACK_2(HelloWorld::uiSliderCallback,this));
return true;
}
void HelloWorld::uiBtnClickCallback(Ref * pSender)
{
Director::getInstance()->end();
}
void HelloWorld::uiSliderCallback(Ref * pSender,cocos2d::ui::Slider::EventType evType)
{
if(pSender){
cocos2d::ui::Slider * ps=(cocos2d::ui::Slider *)pSender;
int iper = ps->getPercent();
Node * nodeParent = ps->getParent();
cocos2d::ui::LoadingBar * pl = (cocos2d::ui::LoadingBar *)nodeParent->getChildByTag(10);
pl->setPercent(iper);
}else{
log(“CocosUIScene Slider Callback Error!!”);
}
}
大家应该看出来了吧,这代码的原理是从CSB中直接按照标签查找出需要回调的组件,并各自注册相关的事件,并在对应的函数中处理。
这是响应 Slider 拖动的事件,把 LoadingBar 的值对应修改,点击 button 会退出APP
这样只要跟 UI 固定好标签就可以,后续有新增加的组件也不会报错,只是没有事件处理而已,但是删除带事件的组件就会出问题(但可以优化代码来避免)