在如今手遊競争激烈的情況,時間決定成敗,lua的支援熱更新(免去平台稽核的時間),小巧,快速高效,是以lua開發是手遊不可少的利器,接下來會精力把重點放在lua上面。
首先cocos2dx實作在appdelegate.cpp中通過c++調用lua,作為調用lua的入口,代碼如下:
bool AppDelegate::applicationDidFinishLaunching()
{
// initialize director
CCDirector *pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
// turn on display FPS
pDirector->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60);
// register lua engine
CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
CCLuaStack *pStack = pEngine->getLuaStack();
lua_State *tolua_s = pStack->getLuaState();
tolua_extensions_ccb_open(tolua_s);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
pStack = pEngine->getLuaStack();
tolua_s = pStack->getLuaState();
tolua_web_socket_open(tolua_s);
#endif
std::vector<std::string> searchPaths;
searchPaths.push_back("cocosbuilderRes");
searchPaths.insert(searchPaths.begin(), "scenetest/LoadSceneEdtiorFileTest");
#if CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY
searchPaths.push_back("TestCppResources");
searchPaths.push_back("script");
#endif
CCFileUtils::sharedFileUtils()->setSearchPaths(searchPaths);
pEngine->executeScriptFile("luaScript/scene.lua");
return true;
}
加上頭檔案:#include "CCLuaEngine.h" #include "Lua_extensions_CCB.h" #include "Lua_web_socket.h"
這是c++調用lua 的入口函數,接下來就是 lua之間的互相調用,遊戲的邏輯處理。
場景是遊戲中最重要的組成部分,是承載者整個遊戲元素的容器,接下來就從從場景入手學習 cocos2dx是如何用lua進行開發的。
注釋:建立一個場景,然後加入一個層,在該層上建立一個精靈,并讓該重精靈重複執行旋轉360度。
---- SceneTest
local scene=CCScene:create()
local layer=sceneTestLayer1()
scene:addChild(layer,0)
CCDirector:shareDirector():runWihScene(scene);
sceneTestLayer1=function()
local layer=CCLayer:create()
local size=CCDirector:shareDirector():getWinSize()
local sprite=CCSprite:create("test.png");
layer:addChild(sprite)
sprite:setposition(ccp(size.width/2,size.height/2))
local rotate=CCRotateBy:create(2,360)
local repeat_action=CCRepeatForever:create(rotate)
sprite:runAction(repeat_action)
return ret
end