cocos2dx 3.1.1 線上熱更新 自動更新(使用AssetsManager更新遊戲資源套件),cocos2dx熱更新
為什麼要線上更新資源和指令檔?
簡單概括,如果你的遊戲項目已經在google play 或Apple Store 等平台上架了,那麼當你項目需要做一些活動或者修改前端的一些代碼等那麼你需要重新提交一個新版本給平台。但是平台審核和具體的上架時間是個不確定的。具體什麼時候能上架,主要由具體的平台決定。
如果遊戲項目是使用指令碼語言進行編寫的(如lua、js),那麼一旦需要更新,則可以通過從伺服器下載最新的指令碼和資源,從而跳過平台直接實現線上更新。(有些平台是禁止線上更新資源方式的,但是你懂得)
閑話少說,本文主要是解決如何在項目中實現線上更新:
我們這裡用的是cocos2dx的類AssertsMananger,它在引擎的extensions\assets-manager可以看到。
AssetsManager傳三個參數,資源的zip包路徑,version路徑,寫檔案的路徑。
然後調用AssetsManager的update函數進行下載更新。
設定資源套件名稱
這裡繼續沿用cocos2dx的AssetsManager類中預設的名稱:cocos2dx-update-temp-package.zip。
如果想要修改檔案名稱,可以直接修改引擎下 extensions\assets-manager\AsetsManager.ccp中的TEMP_PACKAGE_FILE_NAME
選定伺服器位址和設定版本號碼 我這裡用的是參考資料一,Nels的個人空間(部落格地址http://www.58player.com/blog-2537-95913.html)他的資源套件路徑和本版號。 http://shezzer.sinaapp.com/downloadTest/cocos2dx-update-temp-package.zip
http://shezzer.sinaapp.com/downloadTest/version.php
C++代碼實現
建立Upgrade類,繼承自CCLayer編輯Upgrade.h檔案內容如下:
// Upgrade.h// Created by Sharezer on 14-11-23.// #ifndef _UPGRADE_H_#define _UPGRADE_H_#include "cocos2d.h"#include "extensions/cocos-ext.h" class Upgrade : public cocos2d::CCLayer, public cocos2d::extension::AssetsManagerDelegateProtocol{public: Upgrade(); virtual ~Upgrade(); virtual bool init(); void upgrade(cocos2d::Ref* pSender);//檢查版本更新 void reset(cocos2d::Ref* pSender); //重設版本 virtual void onError(cocos2d::extension::AssetsManager::ErrorCode errorCode); //錯誤資訊 virtual void onProgress(int percent);//更新下載進度 virtual void onSuccess(); //下載成功 CREATE_FUNC(Upgrade);private: cocos2d::extension::AssetsManager* getAssetManager(); void initDownloadDir(); //建立下載目錄 private: std::string _pathToSave; cocos2d::Label *_showDownloadInfo;}; #endif
修改Upgrade.cpp檔案如下:
//Upgrade.cpp#include "Upgrade.h"#include "CCLuaEngine.h" #if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)#include <dirent.h>#include <sys/stat.h>#endif USING_NS_CC;USING_NS_CC_EXT; #define DOWNLOAD_FIEL "download"//下載後儲存的檔案夾名 Upgrade::Upgrade():_pathToSave(""),_showDownloadInfo(NULL){ } Upgrade::~Upgrade(){ AssetsManager* assetManager = getAssetManager(); CC_SAFE_DELETE(assetManager);} bool Upgrade::init(){ if (!CCLayer::init()) { return false; } Size winSize = Director::getInstance()->getWinSize(); initDownloadDir(); _showDownloadInfo = Label::createWithSystemFont("", "Arial", 20); this->addChild(_showDownloadInfo); _showDownloadInfo->setPosition(Vec2(winSize.width / 2, winSize.height / 2 - 20)); auto itemLabel1 = MenuItemLabel::create( Label::createWithSystemFont("Reset", "Arail", 20), CC_CALLBACK_1(Upgrade::reset, this)); auto itemLabel2 = MenuItemLabel::create( Label::createWithSystemFont("Upgrad", "Arail", 20), CC_CALLBACK_1(Upgrade::upgrade, this)); auto menu = Menu::create(itemLabel1, itemLabel2, NULL); this->addChild(menu); itemLabel1->setPosition(Vec2(winSize.width / 2, winSize.height / 2 + 20)); itemLabel2->setPosition(Vec2(winSize.width / 2, winSize.height / 2 )); menu->setPosition(Vec2::ZERO); return true;} void Upgrade::onError(AssetsManager::ErrorCode errorCode){ if (errorCode == AssetsManager::ErrorCode::NO_NEW_VERSION) { _showDownloadInfo->setString("no new version"); } else if (errorCode == AssetsManager::ErrorCode::NETWORK) { _showDownloadInfo->setString("network error"); } else if (errorCode == AssetsManager::ErrorCode::CREATE_FILE) { _showDownloadInfo->setString("create file error"); }} void Upgrade::onProgress(int percent){ if (percent < 0) return; char progress[20]; snprintf(progress, 20, "download %d%%", percent); _showDownloadInfo->setString(progress);} void Upgrade::onSuccess(){ CCLOG("download success"); _showDownloadInfo->setString("download success"); std::string path = FileUtils::getInstance()->getWritablePath() + DOWNLOAD_FIEL; auto engine = LuaEngine::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(engine); if (engine->executeScriptFile("src/main.lua")) { return ; }} AssetsManager* Upgrade::getAssetManager(){ static AssetsManager *assetManager = NULL; if (!assetManager) { assetManager = new AssetsManager("http://shezzer.sinaapp.com/downloadTest/cocos2dx-update-temp-package.zip", "http://shezzer.sinaapp.com/downloadTest/version.php", _pathToSave.c_str()); assetManager->setDelegate(this); assetManager->setConnectionTimeout(8); } return assetManager;} void Upgrade::initDownloadDir(){ CCLOG("initDownloadDir"); _pathToSave = CCFileUtils::getInstance()->getWritablePath(); _pathToSave += DOWNLOAD_FIEL;CCLOG("Path: %s", _pathToSave.c_str());#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) DIR *pDir = NULL; pDir = opendir(_pathToSave.c_str()); if (!pDir) { mkdir(_pathToSave.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); }#else if ((GetFileAttributesA(_pathToSave.c_str())) == INVALID_FILE_ATTRIBUTES) { CreateDirectoryA(_pathToSave.c_str(), 0); }#endif CCLOG("initDownloadDir end");} void Upgrade::reset(Ref* pSender){ _showDownloadInfo->setString(""); // Remove downloaded files#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) string command = "rm -r "; // Path may include space. command += "\"" + _pathToSave + "\""; system(command.c_str());#else std::string command = "rd /s /q "; // Path may include space. command += "\"" + _pathToSave + "\""; system(command.c_str());#endif getAssetManager()->deleteVersion(); initDownloadDir();} void Upgrade::upgrade(Ref* pSender){ _showDownloadInfo->setString(""); getAssetManager()->update(); }
其中 Upgrade::onSuccess()函數中,我這裡調用的是main.lua檔案
auto engine = LuaEngine::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(engine); if (engine->executeScriptFile("src/main.lua")) { return ; }
如果是c++項目,可以自己調用相應的C++檔案。如 #include "HelloWorldScene.h"auto scene = HelloWorld::scene();
Director::getInstance()->replaceScene(scene);
修改AppDelegate.cpp檔案調用Upgrade類
AppDelegate.h無需修改,cpp稍微修改一下就可以了
標頭檔中加入#include "Upgrade.h"主要是修改了AppDelegate::applicationDidFinishLaunching()函數中調用Upgrade類
#include "AppDelegate.h"#include "CCLuaEngine.h"#include "SimpleAudioEngine.h"#include "cocos2d.h"#include "Upgrade.h"using namespace CocosDenshion;USING_NS_CC;using namespace std;AppDelegate::AppDelegate(){}AppDelegate::~AppDelegate(){ SimpleAudioEngine::end();}bool AppDelegate::applicationDidFinishLaunching(){ // initialize director auto director = Director::getInstance();auto glview = director->getOpenGLView();if(!glview) {glview = GLView::createWithRect("dragan", Rect(0,0,900,640));director->setOpenGLView(glview);} glview->setDesignResolutionSize(480, 320, ResolutionPolicy::NO_BORDER); // 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); //auto engine = LuaEngine::getInstance(); //ScriptEngineManager::getInstance()->setScriptEngine(engine); //if (engine->executeScriptFile("src/main.lua")) { // return false; //} auto scene = Scene::create(); auto layer = Upgrade::create(); Director::getInstance()->runWithScene(scene); scene->addChild(layer); 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();}
修改cocos2dx的main.lua我只是把其中一個資源檔名字和路徑參考下載資源套件中的路徑修改了,以便看到資源更新的效果。例如我把農場背景圖片改為了下載資源套件中的3D/CompleteMap.PNG
編譯運行項目:
Reset:用於重設版本號碼,辦刪除下載資源。
Upgrad:校正版本號碼,當有更新時下載新資源。
_pathToSave儲存著檔案的下載路徑,壓縮包下載下來後,將被自動解壓到_pathToSave中。
以win32為例,下載的資源是儲存在Debug.win32\ 中,可以看到我們之前設定的下載目錄download。
onSuccess中,當下載成功後,將跳轉到main.lua中。
這時可以看到該檔案已經直接使用已下載的資源。
______________________________________________________________________________
參考資料:http://www.58player.com/blog-2537-95913.html Nels的個人空間 cocos2dx 3.2引擎版本 lua熱更新 自動更新 http://zengrong.net/post/2131.htm 這個關於lua熱更新的文章也是寫得甚好!十分容易明白,步驟清晰http://blog.csdn.net/xiaominghimi/article/details/8825524 Himi關於熱更新的解析貼 cocos2dx 2.x引擎版本http://blog.csdn.net/cloud95/article/details/38065085 cocos2dx lua熱更新 執行個體版本,語言貌似比較通俗
http://www.cocoachina.com/bbs/simple/?t183552.html cocos關於熱更新的討論帖(關於路徑的討論很經典)http://www.cocoachina.com/bbs/read.php?tid=213066 cocos2dx lua 遊戲熱更新http://lcinx.blog.163.com/blog/static/43494267201210270345232/http://my.oschina.net/u/1785418/blog/283043 基於Quick-cocos2dx 2.2.3 的動態更新實現完整篇。(打包,伺服器介面,模組自更新)http://blog.csdn.net/q277055799/article/details/8463835 lua熱更新原理http://lcinx.blog.163.com/blog/static/43494267201210270345232/ lua 熱更新原理