由于Cocos2d-x3.x的代码和各种乱七八糟的系统实在是混乱,所以笔者最近在研究Cocos2d-x 2.x。网上现在关于2.x的教程着实不多了,又因为Cocos引擎各版本都互相不兼容,所以贴一下Cocos2d-x 2.x与Cocos Studio1.x的交互。
关于Cocos Studio的操作,晚上教程还是有的,就先不贴了,重点放在API与交互的解决上。
关于Cocos2d-x 2.2.6加载UI不响应点击事件的问题有两个:
1、网上指出的根节点应该取消 “交互” 的对勾,不过据说这个只能解决3.0版本中不响应的问题。
2、在2.2.6中,如果UI控件不响应触摸事件,可以看看自己添加控件时用的是addChild()还是addWidget()。前者不会响应触摸事件,后者才可以。
(我的文件中的根节点就是这个Root)
用到的头文件:
CocoStudio\GUI\BaseClasses\UIWidget.h //定义了TouchEventType
CocoStudio\Reader\WidgetReader\WidgetReader.h //主要头文件
命名空间:
using namespace cocos2d;
using namespace cocos2d::ui;
using namespace cocos2d::extension;
下面是源代码,VS2013+Cocos2D-x 2.2.6,应该可以直接复制,没有问题。
#ifndef__HELLOWORLD_SCENE_H__
#define__HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "CocoStudio\GUI\BaseClasses\UIWidget.h"
class HelloWorld : public cocos2d::CCLayer
{
public:
// Here's a difference. Method 'init' in cocos2d-xreturns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// there's no 'id' in cpp, so we recommend returning theclass instance pointer
static cocos2d::CCScene *scene();
// implement the "static node()" methodmanually
CREATE_FUNC(HelloWorld);
void ExitButtonCallBack(CCObject* obj, cocos2d::ui::TouchEventTypeeventType);
};
#endif //__HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h"
#include "CocoStudio\GUI\BaseClasses\UIWidget.h"
#include "CocoStudio\Reader\WidgetReader\WidgetReader.h"
using namespace cocos2d;
using namespace cocos2d::extension;
using namespace cocos2d::ui;
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloWorld *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 ( !CCLayer::init() )
{
return false;
}
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
UILayer *pTouchLayer = UILayer::create();//UI控件的载体,继承自CCLayer
this->addChild(pTouchLayer);
UIWidget *pMapRoot = (Layout *)(GUIReader::shareReader()->widgetFromJsonFile("DemoUI/DemoUI.json"));
//或者
//UIWidget *pMapRoot = (Layout*)(GUIReader::shareReader()->widgetFromBinaryFile("DemoUI/DemoUI.csb"));
pTouchLayer->addWidget(pMapRoot);//重点!!!UILayer添加控件一定不能使用addChild,否则将不响应点击
UIButton *pExitButton =(UIButton *) (pTouchLayer->getWidgetByName("ExitButton"));
//或者
//UIButton *pExitButton =(UIButton*)(UIHelper::seekWidgetByName(pMapRoot, "ExitButton"));
pExitButton->addTouchEventListener(this, toucheventselector(HelloWorld::ExitButtonCallBack));
return true;
}
void HelloWorld::ExitButtonCallBack(CCObject* obj, TouchEventType eventType)
{
CCLOG("Exit Button Click!");
}