【学习笔记】【Cocos2d-x Lua脚本开发】如何使用Lua脚本调用自定义类

来源:互联网 发布:部落冲突围墙升级数据 编辑:程序博客网 时间:2024/04/26 07:18

学习了Himi的博文:点击打开博文链接


步骤:自定义类——>使用tolua++编译到LuaCoco2d.cpp——>Lua脚本调用

具体的操作步骤如下:

步骤一:自定义类

创建自定义类

//DeepSeaHero.h#include "cocos2d.h"using namespace cocos2d;class DeepSeaHero : public CCSprite{public:    static DeepSeaHero* createDeepSeaHero(const char* heroImage);    void spriteInit();};


//DeepSeaHero.cpp#include "DeepSeaHero.h"DeepSeaHero* DeepSeaHero::createDeepSeaHero(const char *heroImage){    DeepSeaHero* pDeepSeaHero = new DeepSeaHero();    if (pDeepSeaHero && pDeepSeaHero->initWithFile(heroImage)) {        pDeepSeaHero->spriteInit();        pDeepSeaHero->autorelease();        return pDeepSeaHero;    }    CC_SAFE_DELETE(pDeepSeaHero);    return NULL;}void DeepSeaHero::spriteInit(void){    CCMessageBox("create DeepSeaHero succeed", "Deep Sea Game Title");}


步骤二:创建DeepSeaHero.pkg文件,配置build.sh文件,使用tolua++编译pkg文件,创建LuaCocos2d.cpp

步骤二.1 创建DeepSeaHero.pkg文件

在xcode中新建一个文件



将其命名为DeepSeaHero.pkg,保存在引擎目录下的tools/tolua++文件夹下。

然后使用textmate这款编辑器或者mac自带的文本编辑器编辑该文件,DeepSeaHero.pkg文件的内容如下:

class DeepSeaHero : public CCSprite{public:    static DeepSeaHero* createDeepSeaHero(const char* heroImage);    void spriteInit();};


使用文本编辑器打开cocos2d引擎目录下的tools/tolua++文件夹下的READ文件,会看到这里有一些须知:

1. Generating the lua<-->C bindings with tolua++    Build scripts for windows (build.bat) and unix (build.sh) are provided    to generate the relevant files after modifying the .pkg files.  These    scripts basically run the following command:        tolua++.exe -L basic.lua -o LuaCocos2d.cpp Cocos2d.pkg    This will generate the bindings file and patch it with come cocos2dx    specific modifications.    On POSIX systems you can also just run "make" to build the bindings    if/when you change .pkg files.2. Writing .pkg files    1) enum keeps the same    2) remove CC_DLL for the class defines, pay attention to multi inherites    3) remove inline keyword for declaration and implementation    4) remove public protect and private    5) remove the decalration of class member variable    6) keep static keyword    7) remove memeber functions that declared as private or protected 

其中第二点指出了写入.pkg文件所应当注意的规则。


将编写好的DeepSeaHero.pkg文件添加到Cocos2d.pkg文件列表当中:



步骤二.2 配置build.sh文件

首先,解压tools/tolua++文件夹下的tolua++.Mac.zip文件,会得到一个tolua++的unix可执行文件,这个文件在后面的“终端”中执行build.sh文件的时候会使用到。
其次,使用编辑器打开tools/tolua++文件夹下的build.sh 文件,将文件的第7行和第18行的内容改成如下内容:


备注:

第7行表示tolua++工具的路径

第18行表示编译生成的LuaCocos2d.cpp文件的导出位置


步骤二.3 使用tolua++编译pkg文件

接下来执行以下步骤:

1.打开Mac"终端",cd到build.sh所在的目录下

命令为: cd 路径


2.运行build.sh文件

命令为: ./build.sh


3.编译完成!

4.这时候,你打开引擎文件夹下的scripting/lua/cocos2dx_support/LuaCocos2d.cpp文件,可以看到它的修改时间就是刚才的时刻。

同时,LuaCocos2d.cpp文件中增加了以下的内容:







最后,需要在LuaCocos2d.h中引用DeepSeaHero.h头文件


步骤三 Lua测试

运行效果



原创粉丝点击