转自:https://blog.csdn.net/song_hui_xiang/article/details/15712417
1、创建自定义类SongCpp.cpp
SongCpp.h
- #ifndef __SongToLua__SongCpp__
- #define __SongToLua__SongCpp__
- #include <iostream>
- #include "cocos2d.h"
- using namespace cocos2d;
- class SongCpp : public CCSprite {
- public:
- static SongCpp* createSongImage(const char* fileName);
- CCLabelTTF* createSongName(const char* name,int fontSize);
- };
- #endif /* defined(__SongToLua__SongCpp__) */
SongCpp.cpp
- #include "SongCpp.h"
- SongCpp* SongCpp::createSongImage(const char *fileName){
- SongCpp* sp = new SongCpp();
- if (sp && sp->initWithFile(fileName)) {
- sp->autorelease();
- return sp;
- }
- CC_SAFE_DELETE(sp);
- return NULL;
- }
- CCLabelTTF* SongCpp::createSongName(const char *name,int fontSize){
- CCLabelTTF* name_sp = CCLabelTTF::create(name, "Arial", fontSize);
- return name_sp;
- }
2、通过自定义类.h(头文件)制作 pkg
在cocos2dx引擎cocos2d-x-2.1.4/tools/tolua++下有编写pkg文件规则说明README文件,翻译如下:
- Writing .pkg files
- 1) enum keeps the same //枚举类型保留不变
- 2) remove CC_DLL for the class defines, pay attention to multi inherites //删除cc_dll的类定义,改用多继承
- 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 //非public的函数都删除
首先通过xcode生成pkg文件或者纯文本文件(后缀改成.pkg)即可,我的SongCpp.pkg如下:
- class SongCpp : public CCSprite {
- static SongCpp* createSongImage(const char* fileName);
- CCLabelTTF* createSongName(const char* name,int fontSize);
- };
然后把SongCpp.pkg文件放到目录/Users/xiangzi/Documents/cocos2d-x-2.1.4/tools/tolua++下 ,在Cocos2d.pkg中注册你的pkg文件,在此文件中的pkg都是会被编译的,如图11:
再找到build.sh文件,修改下列两个路径,如图7:
TOLUA= 为tolua++目录下的tolua++工具 ${TOLUA} 为生成的LuaCocos2d.cpp所放的路径,我们直接把它放到项目中。
接着打开终端,cd到tolua++目录下,输入make命令回车。如图8:
打开项目中新生成的LuaCocos2d.cpp文件,搜索自定义类SongCpp,如果搜到则证明成功,如图9:
然后再打开LuaCocos2d.h,导入我们的自定义类SongCpp.h
- #ifndef __LUACOCOS2D_H_
- #define __LUACOCOS2D_H_
- #ifdef __cplusplus
- #include "SongCpp.h"
- extern "C" {
- #endif
- #include "tolua++.h"
- #ifdef __cplusplus
- }
- #endif
- TOLUA_API int tolua_Cocos2d_open(lua_State* tolua_S);
- #endif // __LUACOCOS2D_H_
3、在Lua项目中使用自定义类:
- local size = CCDirector:sharedDirector():getWinSize()
- local mainLayer = CCLayer:create()
- local song_image = SongCpp:createSongImage("xiangzi.png")
- song_image:setPosition(ccp(size.width*0.5,size.height*0.5))
- mainLayer:addChild(song_image)
- local song_name = song_image:createSongName("song_huixiang",50)
- song_name:setPosition(ccp(size.width*0.5,size.height*0.8))
- mainLayer:addChild(song_name)
- -- run
- local sceneGame = CCScene:create()
- sceneGame:addChild(mainLayer)
- CCDirector:sharedDirector():runWithScene(sceneGame)