您的位置:首页 > 移动开发 > Cocos引擎

【Cocos2d-x Lua笔记二】CocosLuaGame开篇

2014-12-18 11:12 351 查看
   上一节,创建了一个新项目。现在看看里面都有些什么。

    如果用的是3.2版本的引擎默认新建的项目应该是这样的

     


 

如果是用3.3的引擎创建的是这样的



 

显然,第二个简单多了,那么就从简单的说起吧。

 

1.入口文件

打开src目录



cocos目录里就是引擎的代码了,不去管它。而main.lua就是执行Lua代码的入口文件了。那怎么设置入口文件呢?进入工程目录的\frameworks\runtime-src\Classes下(工程里没有这个目录?构建一下win32的runtime就行了。在 Cocos IDE中右键工程--Cocos工具--构建自定义runtime。)。好了看看AppDelegate.cpp

#include "AppDelegate.h"
#include "CCLuaEngine.h"
#include "SimpleAudioEngine.h"
#include "cocos2d.h"
#include "Runtime.h"
#include "ConfigParser.h"
#include "lua_module_register.h"

using namespace CocosDenshion;

USING_NS_CC;
using namespace std;

AppDelegate::AppDelegate()
{
}

AppDelegate::~AppDelegate()
{
SimpleAudioEngine::end();
}

//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};

GLView::setGLContextAttrs(glContextAttrs);
}

bool AppDelegate::applicationDidFinishLaunching()
{
#if (COCOS2D_DEBUG > 0)
// NOTE:Please don't remove this call if you want to debug with Cocos Code IDE
initRuntime();
#endif

// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
Size viewSize = ConfigParser::getInstance()->getInitViewSize();
string title = ConfigParser::getInstance()->getInitViewName();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
extern void createSimulator(const char* viewName, float width, float height, bool isLandscape = true, float frameZoomFactor = 1.0f);
bool isLanscape = ConfigParser::getInstance()->isLanscape();
createSimulator(title.c_str(),viewSize.width,viewSize.height, isLanscape);
#else
glview = cocos2d::GLViewImpl::createWithRect(title.c_str(), Rect(0, 0, viewSize.width, viewSize.height));
director->setOpenGLView(glview);
#endif
}

auto engine = LuaEngine::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
lua_State* L = engine->getLuaStack()->getLuaState();
lua_module_register(L);

// If you want to use Quick-Cocos2d-X, please uncomment below code
// register_all_quick_manual(L);

LuaStack* stack = engine->getLuaStack();
stack->setXXTEAKeyAndSign("2dxLua", strlen("2dxLua"), "XXTEA", strlen("XXTEA"));

//register custom function
//LuaStack* stack = engine->getLuaStack();
//register_custom_function(stack->getLuaState());

#if (COCOS2D_DEBUG > 0)
// NOTE:Please don't remove this call if you want to debug with Cocos Code IDE
startRuntime();
#else
engine->executeScriptFile(ConfigParser::getInstance()->getEntryFile().c_str());
#endif

return true;
}

// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground()
{
Director::getInstance()->stopAnimation();

SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}

// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
Director::getInstance()->startAnimation();

SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}


其中engine->executeScriptFile(ConfigParser::getInstance()->getEntryFile().c_str());这一行就是设置入口Lua文件了。那么ConfigParser::getInstance()->getEntryFile().c_str()跟main.lua又有什么关系呢,同样打开ConfigParser.cpp

#include "json/document.h"
#include "json/filestream.h"
#include "json/stringbuffer.h"
#include "json/writer.h"
#include "ConfigParser.h"

#define CONFIG_FILE "config.json"
#define CONSOLE_PORT 6010
#define UPLOAD_PORT 6020
#define WIN_WIDTH   960
#define WIN_HEIGHT  640

// ConfigParser
ConfigParser *ConfigParser::s_sharedInstance = NULL;
ConfigParser *ConfigParser::getInstance(void)
{
if (!s_sharedInstance)
{
s_sharedInstance = new ConfigParser();
s_sharedInstance->readConfig();
}
return s_sharedInstance;
}

void ConfigParser::readConfig()
{
string fullPathFile = FileUtils::getInstance()->fullPathForFilename(CONFIG_FILE);
string fileContent = FileUtils::getInstance()->getStringFromFile(fullPathFile);

if(fileContent.empty())
return;

if (_docRootjson.Parse<0>(fileContent.c_str()).HasParseError()) {
cocos2d::log("read json file %s failed because of %s", fullPathFile.c_str(), _docRootjson.GetParseError());
return;
}

if (_docRootjson.HasMember("init_cfg"))
{
if(_docRootjson["init_cfg"].IsObject())
{
const rapidjson::Value& objectInitView = _docRootjson["init_cfg"];
if (objectInitView.HasMember("width") && objectInitView.HasMember("height"))
{
_initViewSize.width = objectInitView["width"].GetUint();
_initViewSize.height = objectInitView["height"].GetUint();
if (_initViewSize.height>_initViewSize.width)
{
float tmpvalue = _initViewSize.height;
_initViewSize.height = _initViewSize.width;
_initViewSize.width = tmpvalue;
}

}
if (objectInitView.HasMember("name") && objectInitView["name"].IsString())
{
_viewName = objectInitView["name"].GetString();
}
if (objectInitView.HasMember("isLandscape") && objectInitView["isLandscape"].IsBool())
{
_isLandscape = objectInitView["isLandscape"].GetBool();
}
if (objectInitView.HasMember("entry") && objectInitView["entry"].IsString())
{
_entryfile = objectInitView["entry"].GetString();
}
if (objectInitView.HasMember("consolePort"))
{
_consolePort = objectInitView["consolePort"].GetUint();
if(_consolePort <= 0)
_consolePort = CONSOLE_PORT;
}
if (objectInitView.HasMember("uploadPort"))
{
_uploadPort = objectInitView["uploadPort"].GetUint();
if(_uploadPort <= 0)
_uploadPort = UPLOAD_PORT;
}
if (objectInitView.HasMember("isWindowTop") && objectInitView["isWindowTop"].IsBool())
{
_isWindowTop= objectInitView["isWindowTop"].GetBool();
}
}
}
if (_docRootjson.HasMember("simulator_screen_size"))
{
const rapidjson::Value& ArrayScreenSize = _docRootjson["simulator_screen_size"];
if (ArrayScreenSiz
a520
e.IsArray())
{
for (int i = 0; i<ArrayScreenSize.Size(); i++)
{
const rapidjson::Value& objectScreenSize = ArrayScreenSize[i];
if (objectScreenSize.HasMember("title") && objectScreenSize.HasMember("width") && objectScreenSize.HasMember("height"))
{
_screenSizeArray.push_back(SimulatorScreenSize(objectScreenSize["title"].GetString(), objectScreenSize["width"].GetUint(), objectScreenSize["height"].GetUint()));
}
}
}
}
}

ConfigParser::ConfigParser(void) :
_isLandscape(true),
_isWindowTop(false),
_consolePort(CONSOLE_PORT),
_uploadPort(UPLOAD_PORT),
_viewName("CocosLuaGames"),
_entryfile("src/main.lua"),
_initViewSize(WIN_WIDTH, WIN_HEIGHT)
{
}

rapidjson::Document& ConfigParser::getConfigJsonRoot()
{
return _docRootjson;
}

string ConfigParser::getInitViewName()
{
return _viewName;
}

string ConfigParser::getEntryFile()
{
return _entryfile;
}

Size ConfigParser::getInitViewSize()
{
return _initViewSize;
}

bool ConfigParser::isLanscape()
{
return _isLandscape;
}

bool ConfigParser::isWindowTop()
{
return _isWindowTop;
}
int ConfigParser::getConsolePort()
{
return _consolePort;
}
int ConfigParser::getUploadPort()
{
return _uploadPort;
}
int ConfigParser::getScreenSizeCount(void)
{
return (int)_screenSizeArray.size();
}

const SimulatorScreenSize ConfigParser::getScreenSize(int index)
{
return _screenSizeArray.at(index);
}


在构造函数中已经为_erntryfile赋初值了

ConfigParser::ConfigParser(void) :
_isLandscape(true),
_isWindowTop(false),
_consolePort(CONSOLE_PORT),
_uploadPort(UPLOAD_PORT),
_viewName("CocosLuaGames"),
_entryfile("src/main.lua"),
_initViewSize(WIN_WIDTH, WIN_HEIGHT)
{
}


 

2.main.lua

--设置文件加载路径
cc.FileUtils:getInstance():addSearchPath("src")
cc.FileUtils:getInstance():addSearchPath("res")

-- CC_USE_DEPRECATED_API = true
--require相当于C里的include
require "cocos.init"

-- cclog
--定义了cclog函数,其中(...)的意思是。这个函数为变长函数,即可接受不同数量的实参。比如cclog("pi=%.3f",math.pi) -->pi=3.141
local cclog = function(...)
print(string.format(...))
end

-- for CCLuaEngine traceback
--错误消息与追溯
function __G__TRACKBACK__(msg)
cclog("----------------------------------------")
cclog("LUA ERROR: " .. tostring(msg) .. "\n")
--获取当前执行的调用栈
cclog(debug.traceback())
cclog("----------------------------------------")
return msg
end

local function main()
--垃圾回收器的API。collectgarbage(“collect”)执行一轮完整的垃圾收集周期,收集并释放所有不可到达的对象。
collectgarbage("collect")
--避免内存泄露
-- avoid memory leak
collectgarbage("setpause", 100)
collectgarbage("setstepmul", 5000)
--用过Cocos2d-x C++写的下面肯定很熟悉了
-- initialize director
local director = cc.Director:getInstance()

--turn on display FPS
director:setDisplayStats(true)

--set FPS. the default value is 1.0/60 if you don't call this
director:setAnimationInterval(1.0 / 60)

cc.Director:getInstance():getOpenGLView():setDesignResolutionSize(480, 320, 0)

--create scene
local scene = require("GameScene")
local gameScene = scene.create()
gameScene:playBgMusic()

if cc.Director:getInstance():getRunningScene() then
cc.Director:getInstance():replaceScene(gameScene)
else
cc.Director:getInstance():runWithScene(gameScene)
end

end

--错误处理
local status, msg = xpcall(main, __G__TRACKBACK__)
if not status then
error(msg)
end


 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cocos2d-x lua ide