Cocos2dx 3.1.1 automatic online hot Update (use AssetsManager to update the game Resource Package)

Source: Internet
Author: User

Cocos2dx 3.1.1 automatic online hot Update (use AssetsManager to update the game Resource Package)

Why do I need to update resources and script files online?

To put it simply, if your game project has been launched on platforms such as google play or Apple Store, when your project needs to do some activity or modify the front-end code, you need to submit a new version to the platform. However, the Platform Review and the specific shelving time are uncertain. The specific time when the server can be shelved depends on the specific platform.

If a game project is written in scripting languages (such as lua and js), you can download the latest scripts and resources from the server, this skips the platform and directly implements online updates. (Some platforms prohibit online resource update, but you know)


This article mainly addresses how to implement online update in the project:

Here we use the cocos2dx class AssertsMananger, which can be seen in engine extensions \ assets-manager.

AssetsManager transmits three parameters: the zip package path, version path, and write file path of the resource.

Then, call the update function of AssetsManager to download the update.

Set resource package name
The default name: cocos2dx-update-temp-package.zip in the AssetsManager class of cocos2dx continues here.
To modify the file name, you can directly modify TEMP_PACKAGE_FILE_NAME in extensions \ assets-manager \ AsetsManager. ccp of the engine.

Select Server address and set version number <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Examples/vNfKwc/Su6OsTmVsc7XEuPbIy7/examples + Cgo8YnI + CjxzdHJvbmc + QyYjNDM7JiM0Mzu0 + sLryrXP Continue/sTayN3I58/Co7oKPGJyPgo8cHJlIGNsYXNzPQ = "brush: java;"> // Upgrade. h // Created by configurzer 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); // check the version update void reset (cocos2d: Ref * pSender ); // reset the version virtual void onError (cocos2d: extension: AssetsManager: ErrorCode errorCode); // error message virtual void onProgress (int percent ); // update the download progress virtual void onSuccess (); // CREATE_FUNC (Upgrade); private: cocos2d: extension: AssetsManager * getAssetManager (); void initDownloadDir (); // create the download directory private: std: string _ pathToSave; cocos2d: Label * _ showDownloadInfo;}; # endif

Modify the Upgrade. cpp file as follows:
// Upgrade. cpp # include "Upgrade. h" # include "CCLuaEngine. h" # if (CC_TARGET_PLATFORM! = CC_PLATFORM_WIN32) # include
   
    
# Include
    
     
# Endif USING_NS_CC; USING_NS_CC_EXT; # define DOWNLOAD_FIEL "download" // name of the folder saved after 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 (Upgr Ade: 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 ();}
    
   

The Upgrade: onSuccess () function calls the main. lua file.
    auto engine = LuaEngine::getInstance();    ScriptEngineManager::getInstance()->setScriptEngine(engine);    if (engine->executeScriptFile("src/main.lua")) {          return ;    }
For a c ++ project, you can call the corresponding C ++ file by yourself. For example, # include "HelloWorldScene. h" auto scene = HelloWorld: scene ();
Director: getInstance ()-> replaceScene (scene );

Modify the AppDelegate. cpp file and call the Upgrade class. AppDelegate. h does not need to be modified. cpp can be modified slightly.
Add # include "Upgrade. h" to the header file"The Upgrade class is called in the AppDelegate: applicationDidFinishLaunching () function.
#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();}

Modify main. lua of cocos2dx. I modified the name and path of a resource file by referring to the path in the downloaded resource package to see the resource update effect. For example, I changed the farm background image to download 3D/CompleteMap. PNG from the resource package.
Compile and run the project:

Reset: Used to Reset the version number to delete and download resources.
Upgrad: Verify the version number. When there is an update, download the new resource.

_ PathToSave stores the File Download path. After the package is downloaded, it is automatically decompressed to _ pathToSave. Html Nels personal space cocos2dx 3.2 engine version lua hot update automatic update http://zengrong.net/post/2131.htm this article about lua hot update is also well written! Easy to understand, steps clear http://blog.csdn.net/xiaominghimi/article/details/8825524 Himi on hot update parsing stickers cocos2dx 2. x engine version http://blog.csdn.net/cloud95/article/details/38065085 cocos2dx lua hot update instance version, the language looks more popular
Http://www.cocoachina.com/bbs/simple? T183552.html cocos about hot update discussion post (about paths very classic) http://www.cocoachina.com/bbs/read.php? Tid = 213066 cocos2dx lua game hot update http://lcinx.blog.163.com/blog/static/43494267201210270345232/http://my.oschina.net/u/1785418/blog/283043 Based on Quick-cocos2dx 2.2.3 dynamic update Implementation complete. (Packaging, server interface, module self-Update) http://blog.csdn.net/q277055799/article/details/8463835 lua thermal update principle http://lcinx.blog.163.com/blog/static/43494267201210270345232/ lua thermal update Principle

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.