Cocos2d-x   发布时间:2022-05-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了cocos2dx 3.4 在线热更新 自动更新(使用AssetsManager更新游戏资源包)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

简单概括,如果你的游戏项目已经在google play 或Apple Store 等平台上架了,那么当你项目需要做一些活动或者修改前端的一些代码等那么你需要重新提交一个新版本给平台。但是平台审核和具体的上架时间是个不确定的。具体什么时候能上架,主要由具体的平台决定。

如果游戏项目是使用脚本语言进行编写的(如lua、js),那么一旦需要更新,则可以通过从服务器下载最新的脚本和资源,从而跳过平台直接实现在线更新。(有些平台是禁止在线更新资源方式的,但是你懂得)

@R_275_10588@,本文主要是解决如何在项目中实现在线更新:

我们这里用的是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://www.2cto.com/kf/ware/vc/"

#pragma once
#include "cocos2d.h" 
#include "extensions/cocos-ext.h"
USING_NS_Cc;
USING_NS_CC_EXT;
using namespace std;
class Upgrade : public Layer,public AssetsmanagerDelegateProtocol 
{ 
public:
	Upgrade(); 
	virtual ~Upgrade(); 
	virtual bool init(); 
		
	void upgrade(Ref* pSender);	//检查版本更新 
	void reset(Ref* pSender);		//重置版本
	virtual void onError(Assetsmanager::ErrorCode errorCodE);	 //更新失败时的错误信息 
	virtual void onProgress(int percent);	//更新下载进度 
	virtual void on@R_874_6048@s(); //下载成功
		
	CREATE_FUNC(UpgradE); 
private: 
	Assetsmanager* getAssetManager();	//获取更新资源路径地址
	void initDownloadDir();	 //创建下载目录 
private: 
	std::string _pathToSave; 
	Label *_showDownloadInfo; 
};

//Upgrade.cpp
#include "Upgrade.h"
#include "HelloWorldScene.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",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::on@R_874_6048@s()
{
	_showDownloadInfo->setString("download @R_874_6048@s");
	std::string path = FileUtils::geTinstance()->getWritablePath() + DOWNLOAD_FIEL;

	auto scene = HelloWorld::createScene();
	Director::geTinstance()->replaceScene(scenE); 
}

Assetsmanager* Upgrade::getAssetManager()
{
	static Assetsmanager *assetManager = NULL;
	if (!assetManager)
	{
		//Assetsmanager传三个参数,资源的zip包路径,version路径,写文件的路径。
		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::on@R_874_6048@s()函数中,我这里调用的是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 "HelloWorldScene.h"
#include "Upgrade.h"
USING_NS_Cc;

AppDelegate::AppDelegate() {

}

AppDelegate::~AppDelegate() 
{
}

//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
    //set OpenGL context attributions,now can only set six attributions:
    //red,green,blue,alpha,depth,stencil
    GLContextAttrs glContextAttrs = {8,8,24,8};

    GLView::setGLContextAttrs(glContextAttrs);
}

bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    auto director = Director::geTinstance();
    auto glview = director->getOpenGLView();
    if(!glview) {
        glview = GLViewImpl::create("My Game");
        director->setOpenGLView(glview);
    }

    // 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);

    // create a scene. it's an autorelease object
    //auto scene = HelloWorld::createScene();
    //// run
    //director->runWithScene(scenE);

	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();

    // if you use SimpleAudioENGIne,it must be pause
    // SimpleAudioENGIne::geTinstance()->pauseBACkgroundMusic();
}

// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
    Director::geTinstance()->startAnimation();

    // if you use SimpleAudioENGIne,it must resume here
    // SimpleAudioENGIne::geTinstance()->resumeBACkgroundMusic();
}

修改cocos2dx的main.lua 我只是把其中一个资源文件名字和路径参下载资源包中的路径修改了,以便看到资源更新的效果。 例如我把农场背景图片改为了下载资源包中的3D/CompleteMap.pNG
编译运行项目:


Reset:用于重置版本号,办删除下载资源。
Upgrad:校验版本号,当有更新时下载新资源。
_pathToSave保存着文件的下载路径,压缩包下载下来后,将被自动解压到_pathToSave中。

大佬总结

以上是大佬教程为你收集整理的cocos2dx 3.4 在线热更新 自动更新(使用AssetsManager更新游戏资源包)全部内容,希望文章能够帮你解决cocos2dx 3.4 在线热更新 自动更新(使用AssetsManager更新游戏资源包)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。