7------cocos2dx 3.1.1 在线热更新 自动更新(AssetsManager)

来源:互联网 发布:超滤膜端口连接 编辑:程序博客网 时间:2024/04/30 11:33

为什么要在线更新资源和脚本文件?

简单概括,如果你的游戏项目已经在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 
\ 

下以是我的资源包路径和本版号。

http://shezzer.sinaapp.com/downloadTest/cocos2dx-update-temp-package.zip

http://shezzer.sinaapp.com/downloadTest/version.php

修改Upgrade.h文件如下:

  1. // Upgrade.h
  2. //<img src="http://img.blog.csdn.net/20140728093037654?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTGlhbmdzaGFvemU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />
  3. // Created by Sharezer on 14-07-26.
  4. //
  5. //
  6. #ifndef _UPGRADE_H_
  7. #define _UPGRADE_H_
  8. #include "cocos2d.h"
  9. #include "extensions/cocos-ext.h"
  10. class Upgrade : public cocos2d::CCLayer, public cocos2d::extension::AssetsManagerDelegateProtocol
  11. {
  12. public:
  13. Upgrade();
  14. virtual ~Upgrade();
  15. virtual bool init();
  16. void upgrade(cocos2d::Ref* pSender); //检查版本更新
  17. void reset(cocos2d::Ref* pSender); //重置版本
  18. virtual void onError(cocos2d::extension::AssetsManager::ErrorCode errorCode); //错误信息
  19. virtual void onProgress(int percent); //更新下载进度
  20. virtual void onSuccess(); //下载成功
  21. CREATE_FUNC(Upgrade);
  22. private:
  23. cocos2d::extension::AssetsManager* getAssetManager();
  24. void initDownloadDir(); //创建下载目录
  25. private:
  26. std::string _pathToSave;
  27. cocos2d::Label *_showDownloadInfo;
  28. };
  29. #endif



修改Upgrade.cpp文件如下: 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
//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())
    {
        returnfalse;
    }
    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);
         
    returntrue;
}
         
voidUpgrade::onError(AssetsManager::ErrorCode errorCode)
{
    if(errorCode == AssetsManager::ErrorCode::NO_NEW_VERSION)
    {
        _showDownloadInfo->setString("no new version");
    }
    elseif (errorCode == AssetsManager::ErrorCode::NETWORK)
    {
        _showDownloadInfo->setString("network error");
    }
    elseif (errorCode == AssetsManager::ErrorCode::CREATE_FILE)
    {
        _showDownloadInfo->setString("create file error");
    }
}
         
voidUpgrade::onProgress(intpercent)
{
    if(percent < 0)
        return;
    charprogress[20];
    snprintf(progress,20,"download %d%%", percent);
    _showDownloadInfo->setString(progress);
}
         
voidUpgrade::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()
{
    staticAssetsManager *assetManager = NULL;
    if(!assetManager)
    {
        assetManager = newAssetsManager("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);
    }
    returnassetManager;
}
         
voidUpgrade::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");
}
         
voidUpgrade::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();
}
         
voidUpgrade::upgrade(Ref* pSender)
{
    _showDownloadInfo->setString("");
    getAssetManager()->update();
         
}</sys></dirent.h>

其中 Upgrade::onSuccess()函数中,我这里调用的是main.lua文件
?
1
2
3
4
5
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类
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#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);
 
    returntrue;
}
 
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
voidAppDelegate::applicationDidEnterBackground()
{
    Director::getInstance()->stopAnimation();
 
    SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
 
// this function will be called when the app is active again
voidAppDelegate::applicationWillEnterForeground()
{
    Director::getInstance()->startAnimation();
 
    SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}

修改cocos2dx的main.lua 我只是把其中一个资源文件名字和路径参考下载资源包中的路径修改了,以便看到资源更新的效果。 例如我把农场背景图片改为了下载资源包中的3D/CompleteMap.PNG 
编译运行项目: 
\
Reset:用于重置版本号,办删除下载资源。 
Upgrad:校验版本号,当有更新时下载新资源。 
\

_pathToSave保存着文件的下载路径,压缩包下载下来后,将被自动解压到_pathToSave中。n�


---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


原文链接:http://www.2cto.com/kf/201411/354936.html
著作权归作者所有,转载请联系作者获得授权。

0 0
原创粉丝点击