cocos2dx3.0alpha1加载cocostudio编辑的ui

cocos2dx30alpha1加载cocostudio编辑的ui(完整版)

 

1、   下载cocostudiov1.1.0.0 版本下载地址Download v1.1.0.0

2、   下载cocos2dx30alpha1版本下载地址Downloadv3.0 alpha1

3、   VS2012安装及开发环境配置、python安装及配置、NDK安装及配置、Eclipse安装及配置,网上资源很多,大家可以去参考,主要解决cocos2dx上面的一些问题。

4、   利用cocostudio编辑好ui界面,放置到工程resource目录下面(UI编辑教程自己去官网学习,提供帮助文档地址http://upyun.cocimg.com/CocoStudio/helpdoc/v1.0.0.0/zh/index.html)

5、  导出项及路径。F:\cocos2dx30alpha1\projects\CarDemo\Resources\UI

cocos2dx3.0alpha1加载cocostudio编辑的ui_第1张图片

6、  导出编辑好的UI结构。


7、  使用cocos2dx自带的create_project.py脚本创建工程。(官方有问题,不知你们有没有碰到过,贴上我自己的修改的脚本)

 

#!/usr/bin/python

# create_project.py

# Create cross-platform cocos2d-x project

# Copyright (c) 2012 cocos2d-x.org

# Author: WangZhe

 

# define global variables

PLATFORMS = {

    "cpp" :["ios_mac", "android", "win32","linux"],

    "lua" :["ios_mac", "android", "win32","linux"],

    "javascript" :["ios_mac", "android", "win32"]

}

 

 

# begin

import sys

import os, os.path

import json

import shutil

 

def checkParams():

    from optparse importOptionParser

   

    # set the parser to parse inputparams

    # the correspond variable nameof "-x, --xxx" is parser.xxx

    parser =OptionParser(usage="Usage: %prog -p -k -l \nSample: %prog -p MyGame -kcom.MyCompany.AwesomeGame -l javascript")

   parser.add_option("-p", "--project",metavar="PROJECT_NAME", help="Set a project name")

   parser.add_option("-k", "--package",metavar="PACKAGE_NAME", help="Set a package name forproject")

   parser.add_option("-l", "--language",

                     metavar="PROGRAMMING_NAME",

                     type="choice",

                     choices=["cpp", "lua", "javascript"],

                      help="Majorprogramming language you want to use, should be [cpp | lua | javascript]")

   

    #parse the params

    (opts, args) =parser.parse_args()

 

    # generate our internal params

    context ={}.fromkeys(("language", "src_project_name","src_package_name", "dst_project_name","dst_package_name", "src_project_path", "dst_project_path","script_dir"))

    platforms_list = []

 

    context["script_dir"]= os.path.abspath(os.path.dirname(__file__))

   

    if opts.project:

       context["dst_project_name"] = opts.project

       context["dst_project_path"] =os.path.abspath(os.path.join(context["script_dir"], "..","..", "projects", context["dst_project_name"]))

    else:

        parser.error("-p or--project is not specified")

 

    if opts.package:

       context["dst_package_name"] = opts.package

    else:

        parser.error("-k or--package is not specified")

 

    if opts.language:

       context["language"] = opts.language

    else:

        parser.error("-l or--language is not specified")

                                

    # fill in src_project_name andsrc_package_name according to "language"

    template_dir =os.path.abspath(os.path.join(context["script_dir"], "..","..", "template"))

    if ("cpp" ==context["language"]):

       context["src_project_name"] = "HelloCpp"

       context["src_package_name"] ="org.cocos2dx.hellocpp"

       context["src_project_path"] = os.path.join(template_dir,"multi-platform-cpp")

    elif ("lua" ==context["language"]):

       context["src_project_name"] = "HelloLua"

       context["src_package_name"] ="org.cocos2dx.hellolua"

       context["src_project_path"] = os.path.join(template_dir,"multi-platform-lua")

    elif ("javascript" ==context["language"]):

       context["src_project_name"] = "HelloJavascript"

       context["src_package_name"] ="org.cocos2dx.hellojavascript"

       context["src_project_path"] = os.path.join(template_dir,"multi-platform-js")

    else:

        print ("Your languageparameter doesn\'t exist." \

            "Check correctlanguage option\'s parameter")

        sys.exit()

    platforms_list =PLATFORMS.get(context["language"], [])

    return context, platforms_list

# end of checkParams(context) function

 

def replaceString(filepath, src_string, dst_string):

       content = ""

       f1 = open(filepath,"rb")

       for line in f1:

              strline =line.decode('utf8')

              if src_string instrline:

                     content +=strline.replace(src_string, dst_string)

              else:

                     content +=strline

       f1.close()

       f2 = open(filepath,"wb")

       f2.write(content.encode('utf8'))

       f2.close()

# end of replaceString

 

def processPlatformProjects(context, platform):

    # determine proj_path

    proj_path =os.path.join(context["dst_project_path"], "proj." +platform)

    java_package_path = ""

 

    # read json config file for thecurrent platform

    conf_path =os.path.join(context["script_dir"], "%s.json" % platform)

    f = open(conf_path)

    data = json.load(f)

 

    # rename package path, like"org.cocos2dx.hello" to "com.company.game". This is aspecial process for android

    if platform =="android":

        src_pkg =context["src_package_name"].split('.')

        dst_pkg = context["dst_package_name"].split('.')

 

        java_package_path =os.path.join(*dst_pkg)

 

    # rename files and folders

    for item indata["rename"]:

        tmp =item.replace("PACKAGE_PATH", java_package_path)

        src =tmp.replace("PROJECT_NAME", context["src_project_name"])

        dst =tmp.replace("PROJECT_NAME", context["dst_project_name"])

        ifos.path.exists(os.path.join(proj_path, src)):

           os.rename(os.path.join(proj_path, src), os.path.join(proj_path, dst))

 

    # remove useless files andfolders

    for item indata["remove"]:

        dst =item.replace("PROJECT_NAME", context["dst_project_name"])

        ifos.path.exists(os.path.join(proj_path, dst)):

           shutil.rmtree(os.path.join(proj_path, dst))

   

    # rename package_name. Thisshould be replaced at first. Don't change this sequence

    for item indata["replace_package_name"]:

        tmp =item.replace("PACKAGE_PATH", java_package_path)

        dst =tmp.replace("PROJECT_NAME", context["dst_project_name"])

        ifos.path.exists(os.path.join(proj_path, dst)):

           replaceString(os.path.join(proj_path, dst),context["src_package_name"], context["dst_package_name"])

   

    # rename project_name

    for item indata["replace_project_name"]:

        tmp =item.replace("PACKAGE_PATH", java_package_path)

        dst =tmp.replace("PROJECT_NAME", context["dst_project_name"])

        ifos.path.exists(os.path.join(proj_path, dst)):

           replaceString(os.path.join(proj_path, dst), context["src_project_name"],context["dst_project_name"])

                 

    # done!

    print ("proj.%s\t\t:Done!" % platform)

# end of processPlatformProjects

 

def createPlatformProjects():

    # prepare valid"context" dictionary

    context, platforms_list  = checkParams()

    # print context, platforms_list

 

    # copy"lauguage"(cpp/lua/javascript) platform.proj intococos2d-x/projects//folder

    ifos.path.exists(context["dst_project_path"]):

        print ("Error:" +context["dst_project_path"] + " folder is alreadyexisting")

        print ("Please removethe old project or choose a new PROJECT_NAME in -project parameter")

        sys.exit()

    else:

       shutil.copytree(context["src_project_path"],context["dst_project_path"], True)

 

    # call process_proj from eachplatform's script folder         

    for platform in platforms_list:

       processPlatformProjects(context, platform)

    #    exec "import%s.handle_project_files" % (platform)

    #    exec"%s.handle_project_files.handle_project_files(context)" % (platform)

 

    print ("New project hasbeen created in this path: " +context["dst_project_path"].replace("/tools/project-creator/../..",""))

    print ("Have Fun!")

 

 

 

 

 

# -------------- main --------------

# dump argvs

# print sys.argv

if __name__ == '__main__':

    createPlatformProjects()

 

主要问题是:print函数有问题,增加了复制org代码,便于编译到android系统上。

 

8、  为了方便整理了bat脚本(create_project.bat),保存为cocos2dx30alpha1\tools\project-creator目录下。

 

脚本如下:

@echo off 
echo ====================== 新建 cocos2d-x 3.0 alpha1 工程项目 ==========================
set /p projectName=请输入项目名称(如:cardemo):
if "%projectName%"=="" gotoinputError
set /p packageName=请输入包名(如:com.wd100.demo):
if "%packageName%"=="" gotoinputError  
@set /p lang=-language(cpp):
echo "============= creatingnow........=========================="
python create_project.py -p %projectName% -k%packageName% -l %lang%

pause  
exit  
:inputError  
@echo 项目名称或者包标示名不能为空!  
pause  

 

9、  使用脚本创建好工程(工程目录在F:\cocos2dx30alpha1\projects+工程名),用vs2012打开工程,3.0后必须vs2012以上版本。

cocos2dx3.0alpha1加载cocostudio编辑的ui_第2张图片

10、加入头文件目录、lib包。(盐多不坏菜,根据自己项目需要精简。)

cocos2dx3.0alpha1加载cocostudio编辑的ui_第3张图片

cocos2dx3.0alpha1加载cocostudio编辑的ui_第4张图片

5、程序中包含以下头文件及命名空间:(我统一包含在WDCocosHeader.h中)代码如下。

 

#ifndef __WD_COCOS_HEADER_H__

#define __WD_COCOS_HEADER_H__

 

#include "cocos2d.h"

#include "UILayer.h"

#include "UIHelper.h"

 

#include "cocos-ext.h"//引入扩展类

#include "cocostudio/CCSGUIReader.h"

 

 

#include "UIWidget.h"

#include "UIButton.h"

#include "UILabelAtlas.h"

#include "UISlider.h"

#include "UILoadingBar.h"

 

#include "CCComRender.h"

#include "CCArmature.h"

 

#include "external/Box2D/Box2D.h"

#include "external/Box2D/Dynamics/b2Fixture.h"

#include "b2World.h"

 

 

 

 

 

//添加命名空间

using namespacecocos2d::extension;

using namespacegui;

using namespacecocos2d;

 

using namespacecocostudio;

 

USING_NS_CC;

USING_NS_CC_EXT;

 

 

 

 

#endif

6、现在切换到代码,修改init函数,去掉其他的代码,加入以下代码

UILayer* ul = UILayer::create();
this->addChild(ul, 0, 100);
ul->addWidget(cocostudio::GUIReader::shareReader()->widgetFromJsonFile("UI/Main.ExportJson"));

 

以上经过测试验证,可以运行(3.0资料很少,自己也是摸索出来的,Python脚本、makefile文件都最好了解下)。

 

 

如果要编译到android系统,mk需要修改下。

 

LOCAL_PATH := $(call my-dir)

 

include $(CLEAR_VARS)

 

LOCAL_MODULE := cocos2dcpp_shared

 

LOCAL_MODULE_FILENAME := libcocos2dcpp

 

##----------------------------------

(这下面是我自己文件目录,因为发现find方法有问题,没办法递归查找,如果哪位朋友递归解决了,也麻烦通知下,免得每次添加文件夹还要去修改makefile。)

WD_BASE_DIR := $(LOCAL_PATH)/../../Classes

WD_CPP_DIRS := WDHeader WDScene WDSchedule ./

 

WD_CPP_LIST := $(foreach src_path, \

                                     $(WD_CPP_DIRS), \

                                          $(wildcard$(WD_BASE_DIR)/$(src_path)/*.cpp ) \

                                           )

 

WD_CPP_LIST +=$(wildcard $(LOCAL_PATH)/../../Classes/*.cpp)

 

LOCAL_SRC_FILES := hellocpp/main.cpp

LOCAL_SRC_FILES += $(WD_CPP_LIST:$(LOCAL_PATH)/%=%)

 

 

#输出信息

$(info "******WD_CPP_LIST:"$(WD_CPP_LIST))

$(info "******LOCAL_SRC_FILES:"$(LOCAL_SRC_FILES))

 

#包含头文件

LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \

                  $(LOCAL_PATH)/../../../../cocos \

                  $(LOCAL_PATH)/../../../../cocos/audio/include \

                  $(LOCAL_PATH)/../../../../cocos/editor-support \

                  $(LOCAL_PATH)/../../../../external \

                  $(LOCAL_PATH)/../../../../external/tinyxml2 \

                  $(LOCAL_PATH)/../../../../external/chipmunk/include/chipmunk \

                  $(LOCAL_PATH)/../../../../extensions \

                  $(LOCAL_PATH)/../../../../cocos/gui

                                                     

 

#加载动态库定义

LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static

LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static

LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static

 

LOCAL_WHOLE_STATIC_LIBRARIES += cocostudio_static

LOCAL_WHOLE_STATIC_LIBRARIES += cocos_gui_static

LOCAL_WHOLE_STATIC_LIBRARIES += cocos_extension_static

LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static

 

#包含动态库

include $(BUILD_SHARED_LIBRARY)

 

#引入库文件包

$(call import-module,2d)

$(call import-module,audio/android)

$(call import-module,Box2D)

 

$(call import-module,gui)

$(call import-module,editor-support/cocostudio)

$(call import-module,extensions)

$(call import-module,2d/platform/android)

 

可将以上写入到头文件中提供引用。

 


你可能感兴趣的:(cocos2dx3.0,cocostudio,cocostudio加载UI,cocos2dx3.0)