1. 程式人生 > >【學習筆記】【Cocos2d-x Lua指令碼開發】如何使用Lua指令碼呼叫自定義類

【學習筆記】【Cocos2d-x Lua指令碼開發】如何使用Lua指令碼呼叫自定義類

步驟:自定義類——>使用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測試

執行效果