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

【Cocos2d-x Lua笔记二】CocosLuaGame开篇,第1张

概述   上一节,创建了一个新项目。现在看看里面都有些什么。     如果用的是3.2版本的引擎默认新建的项目应该是这样的         如果是用3.3的引擎创建的是这样的   显然,第二个简单多了,那么就从简单的说起吧。   1.入口文件 打开src目录 cocos目录里就是引擎的代码了,不去管它。而main.lua就是执行Lua代码的入口文件了。那怎么设置入口文件呢?进入工程目录的\framew

上一节,创建了一个新项目。现在看看里面都有些什么。

如果用的是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 platformsvoID AppDelegate::initGLContextAttrs(){    //set OpenGL context attributions,Now can only set six attributions:    //red,green,blue,Alpha,depth,stencil    GLContextAttrs glContextAttrs = {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,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 toovoID AppDelegate::applicationDIDEnterBackground(){    Director::getInstance()->stopAnimation();    SimpleAudioEngine::getInstance()->pauseBackgroundMusic();}// this function will be called when the app is active againvoID 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// ConfigParserConfigParser *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 (ArrayScreenSize.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),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 msgendlocal 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)    endend--错误处理local status,msg = xpcall(main,__G__TRACKBACK__)if not status then    error(msg)end
总结

以上是内存溢出为你收集整理的【Cocos2d-x Lua笔记二】CocosLuaGame开篇全部内容,希望文章能够帮你解决【Cocos2d-x Lua笔记二】CocosLuaGame开篇所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1023532.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存