cocos2dx 3.1.1 在线热更新 自动更新(使用AssetsManager更新游戏资源包)

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

简单概括,如果你的游戏项目已经在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.ziphttp://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 too
void AppDelegate::applicationDidEnterBackground()
{
  Director::getInstance()->stopAnimation();

  SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}

// this function will be called when the app is active again
void 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://blog.csdn.net/cloud95/article/details/38065085   cocos2dx lua热更新 实例版本,语言貌似比较通俗

http://zengrong.net/post/2131.htm  这个关于lua热更新的文章也是写得甚好!十分容易明白,步骤清晰

http://blog.csdn.net/xiaominghimi/article/details/8825524  Himi关于热更新的解析贴  利用AssetsManager实现在线更新脚本文件lua、js、图片等资源(免去平台审核周期)

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 热更新原理

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值