Cocos2d-x 3.2 Lua樣本 AssetsManagerTest(資源管理員),cocos2d3.2lua

來源:互聯網
上載者:User

Cocos2d-x 3.2 Lua樣本 AssetsManagerTest(資源管理員),cocos2d3.2lua
Cocos2d-x 3.2 Lua樣本 AssetsManagerTest(資源管理員)
本篇部落格介紹Cocos2d-x 為我們提供的一個類——AssetsManager在Lua中的使用例子,效果如:



Cocos2d-x 給出的例子是AssetsManagerTest,進入會發現三個功能表項目:

  • enter
  • reset
  • update
enter是進入情境,reset是刪除本地版本,重新設定,update就是更新資源檔。

筆者使用LDT開啟lua-tests測試專案:


在src目錄下找到AssetsManagerTest目錄,查看以下代碼(筆者對其進行了注釋):>>>AsetsManagerModule.lua
--[[資源管理員模組]]--local AssetManagerModule = {}--[[  newScene]]--function AssetManagerModule.newScene(backfunc)  -- 擷取螢幕大小  local winSize = cc.Director:getInstance():getWinSize()  -- 建立新的情境  local newScene = cc.Scene:create()  -- 建立新的層  local layer    = cc.Layer:create()  -- 後台更新  local function backToUpdate()    local scene = backfunc()    if scene ~= nil then      cc.Director:getInstance():replaceScene(scene)    end  end  -- 建立回退菜單  cc.MenuItemFont:setFontName("Arial")  cc.MenuItemFont:setFontSize(24)  local backMenuItem = cc.MenuItemFont:create("Back")  -- 放置在右下角大致的位置  backMenuItem:setPosition(cc.p(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25))  -- 註冊監聽方法  backMenuItem:registerScriptTapHandler(backToUpdate)  -- 建立菜單  local backMenu = cc.Menu:create()  backMenu:setPosition(0, 0)  backMenu:addChild(backMenuItem)  layer:addChild(backMenu,6)  -- 建立標籤  local helloLabel =  cc.Label:createWithTTF("Hello World", s_arialPath, 38)  helloLabel:setAnchorPoint(cc.p(0.5, 0.5))-- 錨點置中  helloLabel:setPosition(cc.p(winSize.width / 2, winSize.height - 40))  layer:addChild(helloLabel, 5)  -- 建立精靈,這裡是一張背景圖  local sprite = cc.Sprite:create("Images/background.png")  sprite:setAnchorPoint(cc.p(0.5, 0.5))-- 錨點置中  sprite:setPosition(cc.p(winSize.width / 2, winSize.height / 2))  layer:addChild(sprite, 0)  newScene:addChild(layer)-- 添加到情境  cc.Director:getInstance():replaceScene(newScene)-- 替換情境end-- 返回模組return AssetManagerModule

>>>AssetsManagerTest.lua
-- 擷取目標平台local targetPlatform = cc.Application:getInstance():getTargetPlatform()local lineSpace = 40 -- 行間距local itemTagBasic = 1000 local menuItemNames ={    "enter",    "reset",    "update",}-- 擷取螢幕大小local winSize = cc.Director:getInstance():getWinSize()-- 更新層local function updateLayer()    -- 首先建立一個層    local layer = cc.Layer:create()    local support  = false    -- 判斷是否支援iphone、ipad、win32、android或者mac    if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform)         or (cc.PLATFORM_OS_WINDOWS == targetPlatform) or (cc.PLATFORM_OS_ANDROID == targetPlatform)         or (cc.PLATFORM_OS_MAC  == targetPlatform) then        support = true    end    -- 如果不支援平台    if not support then        print("Platform is not supported!")        return layer    end    local isUpdateItemClicked = false -- 是否更新項被點擊    local assetsManager       = nil -- 資源管理員對象    local pathToSave          = ""  -- 儲存路徑    local menu = cc.Menu:create() -- 菜單    menu:setPosition(cc.p(0, 0))  -- 設定菜單位置    cc.MenuItemFont:setFontName("Arial")-- 設定菜單字型樣式    cc.MenuItemFont:setFontSize(24) -- 設定字型大小    -- 用於更新的標籤    local progressLable = cc.Label:createWithTTF("",s_arialPath,30)    progressLable:setAnchorPoint(cc.p(0.5, 0.5))    progressLable:setPosition(cc.p(140,50))    layer:addChild(progressLable)    -- 下載目錄    pathToSave = createDownloadDir()    -- 下載錯誤回調    local function onError(errorCode)        -- 沒有新版本        if errorCode == cc.ASSETSMANAGER_NO_NEW_VERSION then            progressLable:setString("no new version")        elseif errorCode == cc.ASSETSMANAGER_NETWORK then            -- 網路錯誤            progressLable:setString("network error")        end    end    -- 進度更新回調    local function onProgress( percent )        -- 顯示下載進度        local progress = string.format("downloading %d%%",percent)        progressLable:setString(progress)    end        -- 下載成功方法回調    local function onSuccess()        progressLable:setString("downloading ok")    end      -- 獲得資源管理員    local function getAssetsManager()        if nil == assetsManager then            -- 建立一個資源管理員,第一個參數是zip包,第二個參數是版本檔案,第三個參數是儲存路徑            assetsManager = cc.AssetsManager:new("https://raw.github.com/samuele3hu/AssetsManagerTest/master/package.zip",                                           "https://raw.github.com/samuele3hu/AssetsManagerTest/master/version",                                           pathToSave)            -- 保留所有權,該方法會增加Ref對象的引用計數            assetsManager:retain()            -- 設定一系列委託            assetsManager:setDelegate(onError, cc.ASSETSMANAGER_PROTOCOL_ERROR )            assetsManager:setDelegate(onProgress, cc.ASSETSMANAGER_PROTOCOL_PROGRESS)            assetsManager:setDelegate(onSuccess, cc.ASSETSMANAGER_PROTOCOL_SUCCESS )            assetsManager:setConnectionTimeout(3)-- 設定連線逾時        end        return assetsManager    end    -- 更新    local function update(sender)        progressLable:setString("")        -- 調用AssetsManager的update方法        getAssetsManager():update()    end    -- 重設    local function reset(sender)        progressLable:setString("")        -- 刪除下載路徑        deleteDownloadDir(pathToSave)                -- 刪除版本        getAssetsManager():deleteVersion()               -- 建立下載路徑        createDownloadDir()    end    -- 重新載入模組    local function reloadModule( moduleName )        package.loaded[moduleName] = nil              return require(moduleName)    end    -- 進入    local function enter(sender)        -- 如果更新按鈕沒有被點擊        if not isUpdateItemClicked then            local realPath = pathToSave .. "/package"            addSearchPath(realPath,true)        end                -- 重新載入模組        assetsManagerModule = reloadModule("src/AssetsManagerTest/AssetsManagerModule")        assetsManagerModule.newScene(AssetsManagerTestMain)    end    -- 回調方法    local callbackFuncs =    {        enter,        reset,        update,    }    -- 菜單回調方法    local function menuCallback(tag, menuItem)        local scene = nil        local nIdx = menuItem:getLocalZOrder() - itemTagBasic        local ExtensionsTestScene = CreateExtensionsTestScene(nIdx)        if nil ~= ExtensionsTestScene then            cc.Director:getInstance():replaceScene(ExtensionsTestScene)        end    end    -- 遍曆添加三個功能表項目    for i = 1, table.getn(menuItemNames) do        local item = cc.MenuItemFont:create(menuItemNames[i])        item:registerScriptTapHandler(callbackFuncs[i])-- 註冊點擊回調地址        -- 設定三個菜單的位置        item:setPosition(winSize.width / 2, winSize.height - i * lineSpace)        if not support then            item:setEnabled(false)        end        menu:addChild(item, itemTagBasic + i)    end    local function onNodeEvent(msgName)        if nil ~= assetsManager then            -- 釋放資源            assetsManager:release()            assetsManager = nil        end    end    -- 註冊層的點擊回調方法    layer:registerScriptHandler(onNodeEvent)        layer:addChild(menu)    return layerend---------------------------------------  AssetsManager Test-------------------------------------function AssetsManagerTestMain()    local scene = cc.Scene:create()    scene:addChild(updateLayer())    scene:addChild(CreateBackMenuItem())    return sceneend

以下這張圖截自官網:

AssetsManager這個類為我們提供了以上這些方法,下面對這些方法逐個進行簡單說明:
建構函式有三個參數:一個是zip,一個是版本檔案網路地址,一個是下載儲存路徑。
checkStoragePath:檢查儲存路徑
checkUpdate:檢查更新,返回bool值
createDirectory:根據平台建立目錄
deleteVersion:刪除本地版本
downLoad:下載檔案
downloadAndUncompress:下載並解壓縮檔案
getConnectionTimeout:獲得連線逾時時間
getDelegate:獲得委派物件
getPackageUrl:獲得壓縮包地址
getStoragePath:獲得儲存地址
getVersion:獲得版本號碼
getVersionFileUrl:獲得版本檔案地址
setConnectionTimeout:設定網路連接逾時
setDelegate:設定委託
setPackageUrl:設定包路徑
setSearchPath:設定優先資源搜尋路徑
setStoragePath:設定儲存路徑
setVersionFileUrl:設定版本檔案路徑
uncompress:解壓縮檔案
update:更新



這裡還要介紹一個委託類: AssetsManagerDelegateProtocol,我們在實現下載更新時需要回調的三個方法:

讀者可以稍微研讀一下以上代碼,這裡Cocos2d-x只是給出一個簡單使用AssetsManager對程式進行熱更新的例子,但沒有提供完整的解決方案。後面筆者也會對Lua對Cocos2d-x用戶端進行熱更新這部分進行研究,有機會跟大家分享一下這方面的知識。

VS2010裡面建立cocos2D-x項目時,選擇Select Lua support: Support Lua(打鉤),產生後報錯,

一些庫檔案沒正確載入,找到相應的庫檔案粘貼到相應位置就好了。別忘記確認下該檔案是否有許可權。
 
cocos2d-x怎與Lua想結合使用 具體點

cocos2d-x帶有lua引擎了。看看這個。雖然是英語,但是很容易懂。
Cocos2d-x NEW Lua Engine README
Main features
Support autorelease CCObject object.
Call Lua function from C++ (local, global, closure), avoid memory leaks.
Add CCNode:setPosition(x, y), CCNode::getPosition() huge performance boost.
Remove needless class and functions from tolua++ .pkg files, improved performance.
CCMenuItem events handler.
CCNode onEnter/onExit events handler.
CCLayer touch & multi-touches events handler.
看看這2個串連。
www.cocos2d-x.org/...uments
Scripting and Translating between Programming Languages
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.