setDesignResolutionSize()

本文介绍了如何使用cocos2d-x框架通过setDesignResolutionSize()函数来设置虚拟分辨率,从而实现在不同分辨率设备上的自适应显示。详细解释了设置虚拟分辨率后,如何自动缩放显示内容,以及全局缩放比例的设定原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个函数用于指定一个 OpenGL 视图,然后将这个视图映射到设备屏幕上。根据不同的设定,视图会自动缩放显示内容,为 cocos2d-x 自适应多种分辨率提供了基本支持。setDesignResolutionSize() 设置虚拟分辨率后,会指定一个全局的缩放比例,所有的图片即便是 scale = 100%,也会自动缩放~

// ====== 改进的环境修复代码 ====== (function() { // 1. 检测是否在原生平台 if (cc.sys.isNative) { try { console.log('Applying environment fix for', cc.sys.os); // 2. 获取全局对象的更可靠方法 const getGlobalObject = () => { // 尝试 Cocos Creator 的全局对象 if (typeof cc !== 'undefined' && cc.game && cc.game.globalObject) { return cc.game.globalObject; } // Node.js 环境 if (typeof global !== 'undefined') return global; // 浏览器环境 if (typeof window !== 'undefined') return window; // Web Worker 环境 if (typeof self !== 'undefined') return self; // 终极回退 return Function('return this')() || {}; }; const globalObj = getGlobalObject(); // 3. 修复关键全局变量 if (typeof global === 'undefined') { global = globalObj; console.log('Fixed global'); } if (typeof self === 'undefined') { self = globalObj; console.log('Fixed self'); } // 4. 确保全局对象链完整 if (typeof globalThis === 'undefined') { globalThis = globalObj; } // 5. 验证修复结果 console.log('Environment verification:'); console.log('typeof global:', typeof global); console.log('typeof self:', typeof self); console.log('self === global:', self === global); // 6. 特殊修复:确保全局对象上有 self 属性 if (globalObj && typeof globalObj.self === 'undefined') { Object.defineProperty(globalObj, 'self', { value: globalObj, writable: false, configurable: false, enumerable: false }); console.log('Added self to global object'); } } catch (e) { console.error('Environment fix failed:', e); } } else { console.log('Skipping environment fix for non-native platform'); } })(); // ====== 环境修复结束 ====== // 在环境修复后立即验证 setTimeout(() => { console.log('Environment verification after fix:'); console.log('self defined:', typeof self !== 'undefined'); console.log('global defined:', typeof global !== 'undefined'); console.log('self === global:', self === global); console.log('globalThis === self:', globalThis === self); // 尝试访问典型全局属性 try { console.log('self.setTimeout test:', typeof self.setTimeout); } catch (e) { console.error('Global access failed:', e); } }, 100); // 兼容 JSB 环境:确保 self 存在 if (typeof self === 'undefined') { self = globalThis || global || window || {}; console.warn('Fallback self initialization'); } cc.game.onStart = function() { // 1. 初始化游戏设置 cc.view.enableRetina(true); cc.view.resizeWithBrowserSize(true); // 2. 调整设计分辨率和适配策略 cc.view.setDesignResolutionSize(960, 640, cc.ResolutionPolicy.SHOW_ALL); // 3. 加载重力引擎 SDK(核心位置) loadGravityEngineSDK(); // 4. 加载启动场景 cc.assetManager.loadBundle('main', (err) => { if (err) return console.error('Bundle load failed:', err); cc.director.loadScene('start'); }); }; function loadGravityEngineSDK() { const primaryPath = 'src/assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js'; const fallbackPath = 'assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js'; cc.assetManager.loadScript(primaryPath, (err) => { if (err) { console.error('Failed to load gravityengine SDK (primary):', err); // 尝试备用路径 console.log('Trying fallback path:', fallbackPath); cc.assetManager.loadScript(fallbackPath, (altErr) => { if (altErr) { console.error('Fallback load failed:', altErr); handleSDKLoadFailure(); } else { console.log('GravityEngine SDK loaded from fallback'); initGravityEngine(); } }); } else { console.log('GravityEngine SDK loaded successfully'); initGravityEngine(); } }); } function initGravityEngine() { // 确保 SDK 已加载 if (typeof GravityEngine === 'undefined') { console.error('GravityEngine SDK not available after loading!'); return; } // 初始化 SDK GravityEngine.init({ appId: 'YOUR_APP_ID', enableLog: true }); console.log('GravityEngine initialized'); } function handleSDKLoadFailure() { // 降级处理:禁用相关功能或显示提示 console.warn('SDK load failed, disabling analytics features'); window.trackEvent = () => {}; // 空函数降级 } cc.game.run(); var i; Object.defineProperty(exports, "__esModule", { value: true }); var r_Const_Common = require("Const_Common"); var r_GravityPlatform = require("GravityPlatform"); var r_YpNetMag = require("YpNetMag"); var r_EvenType = require("EvenType"); var r_PlayerDataManager = require("PlayerDataManager"); var r_ExcelLoader = require("ExcelLoader"); var r_GameDataManager = require("GameDataManager"); var r_GameGlobalVariable = require("GameGlobalVariable"); var r_UIConfig_Game = require("UIConfig_Game"); var r_UIConfig_Home = require("UIConfig_Home"); var r_BundleConfig = require("BundleConfig"); var r_GameConfig = require("GameConfig"); var r_AudioManager = require("AudioManager"); var r_EventManager = require("EventManager"); var r_HttpManager = require("HttpManager"); var r_LogManager = require("LogManager"); var r_ResLoader = require("ResLoader"); var r_UIManager = require("UIManager"); var r_UIView = require("UIView"); var _decorator = cc._decorator; var _ccclass = _decorator.ccclass; var _property = _decorator.property; var def_UI_Entry = function (e) { function _ctor() { var t = null !== e && e.apply(this, arguments) || this; t.progress_loading = null; return t; } __extends(_ctor, e); _ctor.prototype.onLoad = function () { cc.director.getCollisionManager().enabled = true; }; _ctor.prototype._show = function () { return __awaiter(this, undefined, Promise, function () { var e; var t = this; return __generator(this, function () { this.progress_loading.progress = 0; if (cc.sys.isBrowser) { YPSDK.init(39, "https://platform-shop-dev.hanyougame.com", { gameChannelList: { h5: { platformType: "h5", describe: "默认 H5 渠道", version: "1.0.0" }, tt: { platformType: "tt", appId: "tt09297f94961f881b02", describe: "默认 TT 渠道", version: "1.0.0" }, wx: { platformType: "wx", appId: "wx6baaaa27ab5186ff", describe: "默认 WX 渠道", version: "1.0.0" } } }); YPSDK.login(); } e = cc.tween(this).delay(10).call(function () { console.error("10s后,仍然未登录成功,直接进入游戏"); t.startLoadGame(); }).start(); YPSDK.setLoginCallBack(function (o) { return __awaiter(t, undefined, undefined, function () { return __generator(this, function () { if (o) { r_GravityPlatform.default.GA_Init(YPSDK.Platform.loginData.bindingId); e.stop(); this.startLoadGame(); } return [2]; }); }); }); return [2]; }); }); }; _ctor.prototype.startLoadGame = function () { var e = []; e.push(this._loadGameConfig); e.push(this._loadRemoteConfig); e.push(this._loadExcelData); e.push(this._loadUserData); e.push(this._loadCommonBundle); e.push(this._loadMainBundle); this._completeTasks(e, this._loadGame); cc.sys.platform == cc.sys.WECHAT_GAME && mg.showShareMenu({ menus: ["shareAppMessage", "shareTimeline"] }); }; _ctor.prototype._loadExcelData = function () { return new Promise(function (e) { var t = new Date().getTime(); r_ExcelLoader.ExcelLoader.loadAll().then(function () { console.log("游戏数据表加载成功", new Date().getTime() - t); e(true); }); }); }; _ctor.prototype._loadGame = function () { cc.sys.platform == cc.sys.WECHAT_GAME && r_LogManager.LogMgr.info("开始游戏!" + mg.getChannel()); this._close(); if (r_PlayerDataManager.PlayerDataMgr.GetGuideIndexByTaskName(r_Const_Common.GuideName.战斗背包) != r_Const_Common.GameBagGuideIndex.引导完结) { r_PlayerDataManager.PlayerDataMgr.GMSetGuideIndex(r_Const_Common.GuideName.战斗背包, r_Const_Common.GameBagGuideIndex.引导初始1); r_GameDataManager.GameDataMgr.ClearGameBagData(); r_GameGlobalVariable.GameGlobalVariable.nowlevel = 1; r_UIManager.default.open(r_BundleConfig.BundleNames.Game, r_UIConfig_Game.UIView_Game.UI_GameView); } else { r_EventManager.EventMgr.dispatchEvent(r_EvenType.EVENT_TYPE.Game_Load_View, true); r_UIManager.default.open(r_BundleConfig.BundleNames.Home, r_UIConfig_Home.UIView_Home.UI_Hall); } this.onInitWhiteName(); }; _ctor.prototype._completeTasks = function (e, t) { var o = this; var n = 0; var i = 0; var a = Promise.resolve(); e.forEach(function (t) { a = a.then(function () { return t(); }).then(function () { n++; o._setProgress(n / e.length); }).catch(function () { i++; }); }); return a.then(function () { 0 == i && t.call(o); }); }; _ctor.prototype._loadGameConfig = function () { var e = this; return new Promise(function (t, o) { return __awaiter(e, undefined, undefined, function () { var e; var n; return __generator(this, function (i) { switch (i.label) { case 0: e = new Date().getTime(); return [4, r_ResLoader.default.loadRes("resources", "config/GameConfig", cc.JsonAsset)]; case 1: if (n = i.sent()) { r_GameConfig.default.appConfig = n.json; console.log("Load game config success:", r_GameConfig.default.appConfig); n.decRef(); t(true); console.log("游戏本地配置加载成功", new Date().getTime() - e); } else { console.log("Load game config failure"); o(false); } return [2]; } }); }); }); }; _ctor.prototype._loadRemoteConfig = function () { var e = this; return new Promise(function (t, o) { return __awaiter(e, undefined, undefined, function () { var e; var n; var i; var a; return __generator(this, function (r) { switch (r.label) { case 0: e = new Date().getTime(); if (n = r_GameConfig.default.appConfig.RemoteUrl) { i = cc.path.join(n, "ADConfig.json"); return [4, r_ResLoader.default.loadRemote(i, { ext: ".json" })]; } else { return [3, 2]; } case 1: if ((a = r.sent()) && a.json) { r_GravityPlatform.default.videoId = a.json.ADUnitId[0]; r_GameConfig.default.adConfig = a.json; console.log("Load remote config success:", r_GameConfig.default.adConfig); t(true); console.log("远程配置加载成功", new Date().getTime() - e); } else { console.log("Load remote config failure:", i); o(false); } return [3, 3]; case 2: console.log("Load remote config failure: RemoteUrl is null"); o(false); r.label = 3; case 3: return [2]; } }); }); }); }; _ctor.prototype._loadCommonBundle = function () { var e = this; return new Promise(function (t, o) { return __awaiter(e, undefined, undefined, function () { var e; return __generator(this, function () { e = new Date().getTime(); r_ResLoader.default.loadBundle(r_BundleConfig.BundleNames.Common).then(function (n) { console.log("Loaded main bundle", n); if (n) { t(true); console.log("Common分包下载", new Date().getTime() - e); } else { o(false); } }); return [2]; }); }); }); }; _ctor.prototype._loadMainBundle = function () { var e = this; return new Promise(function (t, o) { return __awaiter(e, undefined, undefined, function () { var e; return __generator(this, function () { e = new Date().getTime(); r_ResLoader.default.loadBundle(r_BundleConfig.MainGameBundle).then(function (n) { console.log("Loaded main bundle", n); if (n) { t(true); console.log("Home分包下载", new Date().getTime() - e); } else { o(false); } }); return [2]; }); }); }); }; _ctor.prototype._yp_sdk_init = function () { var e = this; var t = r_GameConfig.default.appConfig.Version; var o = { gameChannelList: { h5: { platformType: "h5", describe: "默认 H5 渠道", version: t }, tt: { platformType: "tt", appId: "tt09297f94961f881b02", describe: "默认 TT 渠道", version: t }, wx: { platformType: "wx", appId: "wx6baaaa27ab5186ff", describe: "默认 WX 渠道", version: t } } }; return new Promise(function (t, n) { return __awaiter(e, undefined, undefined, function () { var e; return __generator(this, function () { e = new Date().getTime(); YPSDK.init(r_GameConfig.default.appConfig.ServerID, r_GameConfig.default.appConfig.ServerUrl, o).then(function () { t(true); console.log("游品服务器初始化", new Date().getTime() - e); }).catch(function () { n(false); }); return [2]; }); }); }); }; _ctor.prototype._yp_sdk_login = function () { var e = this; return new Promise(function (t, o) { return __awaiter(e, undefined, undefined, function () { return __generator(this, function () { YPSDK.login().then(function () { t(true); }).catch(function () { o(false); }); return [2]; }); }); }); }; _ctor.prototype.onInitWhiteName = function () { return __awaiter(this, undefined, undefined, function () { var e; return __generator(this, function () { e = YPSDK.platformUrl + "/User/GetCfgData?userId=" + YPSDK.Platform.loginData.userUid + "&keyId=NoVideo"; console.log("初始化白名单", YPSDK.platformUrl, YPSDK.Platform.loginData.userUid, e); r_HttpManager.HttpMgr.requestData(function (e) { r_LogManager.LogMgr.debug("---后台请求白名单数据-->>>>>>res------", e); e && e.data && e.data.keyData && "true" == e.data.keyData && (r_PlayerDataManager.PlayerDataMgr.WHITE_NAME_NO_VIDEO = true); }, e); return [2]; }); }); }; _ctor.prototype._loadUserData = function () { var e = this; return new Promise(function (t) { return __awaiter(e, undefined, undefined, function () { var e; return __generator(this, function (o) { switch (o.label) { case 0: o.trys.push([0, 2,, 3]); console.error("初始化数据"); r_AudioManager.AudioMgr.init(); r_GameGlobalVariable.GameGlobalVariable.initPeiZhi(); YPSDK.Common.curChannelData.platformType != YPSDK.GamePlatformType.WX && YPSDK.Common.curChannelData.platformType != YPSDK.GamePlatformType.TT || r_YpNetMag.YpNetMag.failSever(function () { r_YpNetMag.YpNetMag.isFail = true; t(true); console.error("数据读取失败"); }); return [4, r_YpNetMag.YpNetMag.initServer(YPSDK.Platform.loginData)]; case 1: o.sent(); return [3, 3]; case 2: e = o.sent(); r_LogManager.LogMgr.error("load user data error:", e); return [3, 3]; case 3: t(true); return [2]; } }); }); }); }; _ctor.prototype._setProgress = function (e) { e = Math.max(0, Math.min(1, e)); this.progress_loading.progress = e; }; __decorate([_property(cc.ProgressBar)], _ctor.prototype, "progress_loading", undefined); return __decorate([_ccclass], _ctor); }(r_UIView.default); exports.default = def_UI_Entry;这个是我的entry代码 结合上述所有问题 给我修改成最终版本
07-15
// ====== 环境修复与全局对象安全 ====== (function() { // 安全获取全局对象的函数(支持严格模式和所有环境) const getGlobalObject = () => { // 1. 优先使用现代标准 globalThis if (typeof globalThis !== 'undefined') return globalThis; // 2. 处理严格模式限制 try { const globalFromFn = Function('return this')(); if (globalFromFn) return globalFromFn; } catch (e) { console.warn('[EnvFix] Function constructor blocked in strict mode'); } // 3. 环境特定对象 if (typeof global !== 'undefined') return global; // Node.js if (typeof window !== 'undefined') return window; // 浏览器 if (typeof self !== 'undefined') return self; // Web Worker // 4. Cocos Creator 原生环境特殊处理 if (typeof cc !== 'undefined' && cc.sys && cc.sys.__globalAdapter) { return cc.sys.__globalAdapter; } // 5. 最后手段:创建新的全局对象 console.error('[EnvFix] Unable to determine global object, creating new'); return {}; }; const globalObj = getGlobalObject(); // 修复关键全局变量(使用 Object.defineProperty 防止覆盖) const defineGlobal = (name, value) => { if (typeof globalObj[name] === 'undefined') { Object.defineProperty(globalObj, name, { value, writable: true, configurable: true, enumerable: true }); console.log(`[EnvFix] Defined global: ${name}`); } }; // 定义关键全局对象 defineGlobal('global', globalObj); defineGlobal('self', globalObj); defineGlobal('globalThis', globalObj); defineGlobal('window', globalObj); // 原生平台特殊处理 if (cc && cc.sys && cc.sys.isNative) { // 确保 XMLHttpRequest 存在 if (typeof XMLHttpRequest === 'undefined') { defineGlobal('XMLHttpRequest', function() { return cc.loader.getXMLHttpRequest(); }); } // 确保 document 对象存在 if (typeof document === 'undefined') { defineGlobal('document', { createElement: () => ({ appendChild: () => {} }), head: { appendChild: () => {} }, body: { appendChild: () => {} } }); } // 确保 location 对象存在 if (typeof location === 'undefined') { defineGlobal('location', { href: 'file://', protocol: 'file:', hostname: 'localhost', host: 'localhost', origin: 'file://' }); } console.log('[EnvFix] Native environment patched'); } // 确保 require 函数存在 if (typeof globalObj.require === 'undefined') { defineGlobal('require', function(module) { if (globalObj.__modules && globalObj.__modules[module]) { return globalObj.__modules[module]; } console.warn(`[RequireFallback] Module '${module}' not found`); return {}; }); } })(); // ====== 引擎初始化保护系统 ====== const EngineReady = (function() { let _promise = null; let _resolve = null; let _isReady = false; let _checkInterval = null; const safeCheckEngine = () => { // 引擎已初始化 if (cc && cc.game && cc.game._isEngineInited) { return true; } // 尝试监听初始化事件 if (cc && cc.game && cc.game.once) { const eventName = cc.game.EVENT_ENGINE_INITED || 'engine-inited'; cc.game.once(eventName, () => { _resolve && _resolve(); _isReady = true; _checkInterval && clearInterval(_checkInterval); }); return true; } return false; }; return { get isReady() { return _isReady; }, get promise() { return _promise; }, init() { if (!_promise) { _promise = new Promise(resolve => { _resolve = () => { _isReady = true; resolve(); _checkInterval && clearInterval(_checkInterval); }; // 首次检查 if (safeCheckEngine()) return; // 轮询检查 _checkInterval = setInterval(() => { safeCheckEngine() && _resolve(); }, 100); }); } return _promise; }, safeAccess(callback) { if (_isReady) { try { return callback(); } catch (e) { console.error('[EngineSafe] Error:', e); } } return _promise.then(callback).catch(e => { console.error('[EngineSafe] Async error:', e); }); } }; })(); EngineReady.init(); // ====== 游戏主入口 ====== async function gameMainEntry() { try { console.log('[Main] Waiting for engine initialization...'); await EngineReady.promise; console.log('[Main] Engine ready'); // 基本引擎配置 EngineReady.safeAccess(() => { if (cc.view) { cc.view.enableRetina(true); cc.view.resizeWithBrowserSize(true); cc.view.setDesignResolutionSize(960, 640, cc.ResolutionPolicy.SHOW_ALL); } }); // 加载SDK await loadGravityEngineSDK(); // 加载启动场景 await loadStartScene(); } catch (error) { console.error('[Main] Initialization failed:', error); try { cc.director.loadScene('start'); } catch (fallbackError) { displayErrorFallback('启动失败\n请重启应用'); } } } // 错误显示后备方案 function displayErrorFallback(message) { try { const errorDiv = document.createElement('div'); errorDiv.style.cssText = ` position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: black; color: white; display: flex; justify-content: center; align-items: center; z-index: 9999; font: 24px Arial, sans-serif; text-align: center; white-space: pre-line; padding: 20px; `; errorDiv.textContent = message; document.body.appendChild(errorDiv); } catch (e) { console.error('[Fallback] Display failed:', e); } } // ====== SDK加载器增强版 ====== async function loadGravityEngineSDK() { // 使用相对路径解决加载问题 const sdkPaths = [ './assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js', '_plugs/lib/gravityengine.mg.cocoscreator.min.js', 'lib/gravityengine.mg.cocoscreator.min.js' ]; for (const path of sdkPaths) { try { // 关键修复:在加载 SDK 前确保全局对象完整 ensureGlobalEnvironment(); // JSB 特殊处理:使用 require 加载 if (cc.sys.isNative && cc.sys.__globalAdapter?.require) { cc.sys.__globalAdapter.require(path); console.log('[SDK] Native require loaded:', path); } else { await loadScript(path); console.log('[SDK] Loaded from:', path); } // 关键修复:加载后再次检查全局对象 ensureGlobalEnvironment(); initGravityEngine(); return; } catch (e) { console.warn('[SDK] Load failed:', path, e.message); } } console.error('[SDK] All paths failed'); handleSDKLoadFailure(); } function ensureGlobalEnvironment() { // 获取全局对象 const getGlobalObject = () => { if (typeof globalThis !== 'undefined') return globalThis; if (typeof global !== 'undefined') return global; if (typeof window !== 'undefined') return window; if (typeof self !== 'undefined') return self; return Function('return this')() || {}; }; const globalObj = getGlobalObject(); // 确保 self 在所有环境中都存在 if (typeof self === 'undefined') { console.warn('[GlobalFix] self is undefined, patching...'); Object.defineProperty(globalObj, 'self', { value: globalObj, writable: true, configurable: true, enumerable: true }); } // 确保其他关键全局对象存在 const requiredGlobals = ['window', 'global', 'globalThis', 'document', 'location']; requiredGlobals.forEach(name => { if (typeof globalObj[name] === 'undefined') { console.warn(`[GlobalFix] ${name} is undefined, patching...`); Object.defineProperty(globalObj, name, { value: globalObj, writable: true, configurable: true, enumerable: true }); } }); // 原生平台特殊处理 if (cc && cc.sys && cc.sys.isNative) { // 确保 location 对象存在 if (typeof location === 'undefined') { Object.defineProperty(globalObj, 'location', { value: { href: 'file://', protocol: 'file:', hostname: 'localhost' }, writable: false, configurable: false, enumerable: true }); } } } function loadScript(path) { return new Promise((resolve, reject) => { // 优先使用 Cocos 的加载系统 if (cc.assetManager?.loadScript) { cc.assetManager.loadScript(path, (err) => { if (err) { // 原生平台特殊处理 if (cc.sys.isNative) { console.warn('[SDK] Using native fallback for script loading'); try { // 原生平台直接执行脚本 const jsb = cc.sys.__globalAdapter; if (jsb && jsb.require) { jsb.require(path); return resolve(); } } catch (nativeError) { console.error('[SDK] Native require failed:', nativeError); } } reject(err); } else { resolve(); } }); return; } // 后备方案:直接创建 script 标签 try { const script = document.createElement('script'); script.src = path; script.onload = () => resolve(); script.onerror = () => reject(new Error(`Failed to load ${path}`)); document.head.appendChild(script); console.warn('[SDK] Using DOM fallback for script loading'); } catch (e) { reject(e); } }); } function initGravityEngine() { let GravityEngine = null; // 1. 尝试标准方式获取 if (typeof GravityEngine === 'function') { console.log('[SDK] GravityEngine found in local scope'); } // 2. 尝试从全局对象中查找 else if (typeof window.GravityEngine === 'function') { GravityEngine = window.GravityEngine; console.warn('[SDK] Found GravityEngine in window object'); } // 3. 尝试从其他全局对象中查找 else if (typeof global.GravityEngine === 'function') { GravityEngine = global.GravityEngine; console.warn('[SDK] Found GravityEngine in global object'); } // 4. 尝试从 self 对象中查找 else if (typeof self.GravityEngine === 'function') { GravityEngine = self.GravityEngine; console.warn('[SDK] Found GravityEngine in self object'); } // 5. 最后尝试从 globalThis 中查找 else if (typeof globalThis.GravityEngine === 'function') { GravityEngine = globalThis.GravityEngine; console.warn('[SDK] Found GravityEngine in globalThis object'); } else { console.error('[SDK] GravityEngine not found'); return; } try { // 使用您的 AppID 624768904 GravityEngine.init({ appId: '624768904', enableLog: true }); console.log('[SDK] GravityEngine initialized with AppID 624768904'); } catch (e) { console.error('[SDK] Init failed:', e); } } function handleSDKLoadFailure() { console.warn('[SDK] Using fallback analytics'); window.GravityEngine = { init: () => console.warn('SDK unavailable'), trackEvent: () => {} }; } // ====== 场景加载器 ====== async function loadStartScene() { try { // 加载主资源包 await new Promise((resolve) => { if (!cc.assetManager?.loadBundle) { console.warn('[Scene] AssetManager unavailable'); return resolve(); } cc.assetManager.loadBundle('main', (err) => { if (err) console.error('[Scene] Bundle load error:', err); resolve(); }); }); // 加载场景 if (cc.director?.loadScene) { cc.director.loadScene('start'); } else { throw new Error('Director unavailable'); } } catch (error) { console.error('[Scene] Load failed:', error); try { cc.director.loadScene('start'); } catch (e) { throw new Error('Fallback scene load failed'); } } } // ====== UI_Entry组件 ====== const { ccclass, property } = cc._decorator; @ccclass export default class UI_Entry extends cc.Component { @property(cc.ProgressBar) progress_loading = null; loginTimeoutHandler = null; onLoad() { EngineReady.safeAccess(() => { try { cc.director.getCollisionManager().enabled = true; this._show(); } catch (e) { console.error('[UI] onLoad error:', e); this.startLoadGame(); } }).catch(e => { console.error('[UI] Engine access error:', e); this.startLoadGame(); }); } onDestroy() { this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler); } async _show() { this.progress_loading.progress = 0; // 平台SDK初始化 if (cc.sys.isBrowser) { try { await this.initYPSDK(); } catch (e) { console.error('[YPSDK] Init failed:', e); this.startLoadGame(); } } else { this.startLoadGame(); } // 登录超时保护 this.setLoginTimeout(); } setLoginTimeout() { if (cc.tween) { this.loginTimeoutHandler = cc.tween(this) .delay(10) .call(() => { console.warn('[Login] Timeout after 10s'); this.startLoadGame(); }) .start(); } else { setTimeout(() => this.startLoadGame(), 10000); } } async initYPSDK() { if (typeof YPSDK === 'undefined') { console.warn('[YPSDK] SDK unavailable'); return; } const config = { gameChannelList: { h5: { platformType: "h5", version: "1.0.0" }, tt: { platformType: "tt", appId: "tt09297f94961f881b02" }, wx: { platformType: "wx", appId: "wx6baaaa27ab5186ff" } } }; await YPSDK.init(39, "https://platform-shop-dev.hanyougame.com", config); await YPSDK.login(); if (YPSDK.setLoginCallBack) { YPSDK.setLoginCallBack(success => { if (!success) return; // 取消超时 this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler); // 初始化分析SDK if (r_GravityPlatform.default?.GA_Init) { r_GravityPlatform.default.GA_Init(YPSDK.Platform.loginData.bindingId); } this.startLoadGame(); }); } else { this.startLoadGame(); } } startLoadGame() { const tasks = [ this._loadGameConfig, this._loadRemoteConfig, this._loadExcelData, this._loadUserData, this._loadCommonBundle, this._loadMainBundle ].map(fn => fn.bind(this)); this.executeTasks(tasks, () => this._loadGame()); } executeTasks(tasks, finalCallback) { let completed = 0; const total = tasks.length; const runTask = async (index) => { if (index >= total) { finalCallback(); return; } try { await tasks[index](); completed++; this._setProgress(completed / total); runTask(index + 1); } catch (e) { console.error(`[Task ${index}] Failed:`, e); completed++; this._setProgress(completed / total); runTask(index + 1); // 继续执行后续任务 } }; runTask(0); } async _loadExcelData() { if (!r_ExcelLoader?.ExcelLoader?.loadAll) { console.warn('[Data] ExcelLoader unavailable'); return; } await r_ExcelLoader.ExcelLoader.loadAll(); console.log('[Data] Excel loaded'); } async _loadGameConfig() { if (!r_ResLoader.default?.loadRes) { console.warn('[Config] ResLoader unavailable'); return; } const jsonAsset = await r_ResLoader.default.loadRes( "resources", "config/GameConfig", cc.JsonAsset ); if (jsonAsset && r_GameConfig.default) { r_GameConfig.default.appConfig = jsonAsset.json; jsonAsset.decRef && jsonAsset.decRef(); console.log('[Config] Game config loaded'); } } async _loadRemoteConfig() { if (!r_GameConfig.default?.appConfig?.RemoteUrl) { console.warn('[Config] RemoteUrl not set'); return; } const remoteUrl = r_GameConfig.default.appConfig.RemoteUrl; const remotePath = cc.path.join(remoteUrl, "ADConfig.json"); try { const remoteConfig = await r_ResLoader.default.loadRemote(remotePath, { ext: ".json" }); if (remoteConfig?.json && r_GravityPlatform.default) { r_GravityPlatform.default.videoId = remoteConfig.json.ADUnitId[0]; r_GameConfig.default.adConfig = remoteConfig.json; console.log('[Config] Remote config loaded'); } } catch (e) { console.error('[Config] Remote load failed:', e); } } async _loadCommonBundle() { if (!r_ResLoader.default?.loadBundle) { console.warn('[Bundle] ResLoader unavailable'); return; } try { await r_ResLoader.default.loadBundle(r_BundleConfig.BundleNames.Common); console.log('[Bundle] Common loaded'); } catch (e) { console.error('[Bundle] Common load failed:', e); } } async _loadMainBundle() { if (!r_ResLoader.default?.loadBundle) { console.warn('[Bundle] ResLoader unavailable'); return; } try { await r_ResLoader.default.loadBundle(r_BundleConfig.MainGameBundle); console.log('[Bundle] Main loaded'); } catch (e) { console.error('[Bundle] Main load failed:', e); } } async _loadUserData() { try { // 音频初始化 r_AudioManager.AudioMgr?.init(); // 全局配置 r_GameGlobalVariable.GameGlobalVariable?.initPeiZhi(); // 网络检测 if (YPSDK?.Common?.curChannelData) { const platformType = YPSDK.Common.curChannelData.platformType; if (platformType === YPSDK.GamePlatformType.WX || platformType === YPSDK.GamePlatformType.TT) { r_YpNetMag.YpNetMag?.failSever(() => { r_YpNetMag.YpNetMag.isFail = true; }); } } // 用户数据初始化 if (YPSDK?.Platform?.loginData) { await r_YpNetMag.YpNetMag?.initServer(YPSDK.Platform.loginData); } } catch (e) { console.error('[User] Load failed:', e); } } _loadGame() { try { const guideIndex = r_PlayerDataManager.PlayerDataMgr.GetGuideIndexByTaskName( r_Const_Common.GuideName.战斗背包 ); if (guideIndex !== r_Const_Common.GameBagGuideIndex.引导完结) { // 新玩家流程 r_PlayerDataManager.PlayerDataMgr.GMSetGuideIndex?.( r_Const_Common.GuideName.战斗背包, r_Const_Common.GameBagGuideIndex.引导初始1 ); r_GameDataManager.GameDataMgr?.ClearGameBagData(); r_GameGlobalVariable.GameGlobalVariable.nowlevel = 1; r_UIManager.default?.open( r_BundleConfig.BundleNames.Game, r_UIConfig_Game.UIView_Game.UI_GameView ); } else { // 老玩家流程 r_EventManager.EventMgr?.dispatchEvent(r_EvenType.EVENT_TYPE.Game_Load_View, true); r_UIManager.default?.open( r_BundleConfig.BundleNames.Home, r_UIConfig_Home.UIView_Home.UI_Hall ); } // 白名单检查 this.checkWhiteList(); } catch (e) { console.error('[Game] Load failed:', e); try { cc.director.loadScene('start'); } catch (sceneError) { console.error('[Game] Scene load failed:', sceneError); } } } async checkWhiteList() { try { if (!YPSDK?.Platform?.loginData || !YPSDK.platformUrl) return; const url = `${YPSDK.platformUrl}/User/GetCfgData?userId=${YPSDK.Platform.loginData.userUid}&keyId=NoVideo`; if (r_HttpManager.HttpMgr?.requestData) { r_HttpManager.HttpMgr.requestData(res => { if (res?.data?.keyData === "true") { r_PlayerDataManager.PlayerDataMgr.WHITE_NAME_NO_VIDEO = true; } }, url); } } catch (e) { console.error('[WhiteList] Check failed:', e); } } _setProgress(progress) { if (!this.progress_loading) return; this.progress_loading.progress = Math.max(0, Math.min(1, progress)); } } // ====== 启动游戏 ====== if (cc?.game?.run) { cc.game.run(() => { // 确保环境修复完成 ensureGlobalEnvironment(); gameMainEntry(); }); } else { setTimeout(() => { ensureGlobalEnvironment(); gameMainEntry(); }, 1000); } 针对上述问题 给我修改后的完整代码
最新发布
07-16
// ====== 环境修复代码(确保全局对象安全) ====== (function() { if (cc && cc.sys && cc.sys.isNative) { try { console.log('[EnvFix] Applying environment patches for', cc.sys.os); // 可靠获取全局对象的多平台兼容方案 const getGlobalObject = () => { // 优先级1: Cocos Creator 的全局对象 if (typeof cc !== 'undefined' && cc.game && cc.game.globalObject) { return cc.game.globalObject; } // 优先级2: Node.js 环境 if (typeof global !== 'undefined') return global; // 优先级3: 浏览器环境 if (typeof window !== 'undefined') return window; // 优先级4: Web Worker 环境 if (typeof self !== 'undefined') return self; // 终极回退方案 return Function('return this')() || {}; }; const globalObj = getGlobalObject(); // 修复关键全局变量缺失问题 if (typeof global === 'undefined') global = globalObj; if (typeof self === 'undefined') self = globalObj; if (typeof globalThis === 'undefined') globalThis = globalObj; // 确保全局对象上有 self 属性 if (globalObj && typeof globalObj.self === 'undefined') { Object.defineProperty(globalObj, 'self', { value: globalObj, writable: false, configurable: false, enumerable: false }); console.log('[EnvFix] Added self to global object'); } // 验证修复结果 console.log('[EnvFix] Verification:', { global: typeof global, self: typeof self, globalThis: typeof globalThis, equality: self === global && global === globalThis }); } catch (e) { console.error('[EnvFix] Failed:', e); } } else { console.log('[EnvFix] Skipping for non-native platform'); } })(); // ====== 改进的引擎初始化保护系统 ====== const EngineReady = (function() { let _promise = null; let _resolve = null; let _isReady = false; let _checkInterval = null; return { get isReady() { return _isReady; }, get promise() { return _promise; }, init() { if (!_promise) { _promise = new Promise(resolve => { _resolve = () => { _isReady = true; resolve(); if (_checkInterval) { clearInterval(_checkInterval); _checkInterval = null; } }; // 安全检查:确保cc.game存在 const safeCheckEngine = () => { // 如果引擎已经初始化 if (cc && cc.game && cc.game._isEngineInited) { _resolve(); return true; } // 尝试监听引擎初始化事件 if (cc && cc.game && cc.game.once) { // 使用更安全的方式访问事件常量 const eventName = (cc.game && cc.game.EVENT_ENGINE_INITED) || (cc.Game && cc.Game.EVENT_ENGINE_INITED) || 'engine-inited'; cc.game.once(eventName, _resolve); return true; } return false; }; // 首次尝试检查 if (safeCheckEngine()) { return; } // 如果首次检查失败,设置轮询检查 _checkInterval = setInterval(() => { if (safeCheckEngine()) { clearInterval(_checkInterval); _checkInterval = null; } }, 100); }); } return _promise; }, // 安全访问引擎API的包装器 safeAccess(callback) { if (_isReady) { try { return callback(); } catch (e) { console.error('[EngineSafe] Callback error:', e); } } return _promise.then(callback).catch(e => { console.error('[EngineSafe] Async callback error:', e); }); } }; })(); // 初始化但不立即等待 EngineReady.init(); // ====== 游戏主入口 ====== async function gameMainEntry() { try { console.log('[Main] Waiting for engine initialization...'); // 安全等待引擎初始化 await EngineReady.promise; console.log('[Main] Engine fully initialized'); // 安全初始化游戏设置 EngineReady.safeAccess(() => { if (cc.view) { cc.view.enableRetina(true); cc.view.resizeWithBrowserSize(true); cc.view.setDesignResolutionSize(960, 640, cc.ResolutionPolicy.SHOW_ALL); } }); // 加载重力引擎SDK await loadGravityEngineSDK(); // 加载启动场景 await loadStartScene(); } catch (error) { console.error('[Main] Game initialization failed:', error); // 尝试恢复基本功能 try { // 直接尝试加载场景 if (cc.director && cc.director.loadScene) { cc.director.loadScene('start'); } } catch (fallbackError) { console.error('[Main] Fallback scene load failed:', fallbackError); // 最终后备方案 displayErrorFallback('Initialization Failed\nPlease Restart'); } } } // 错误显示后备方案 function displayErrorFallback(message) { try { // 尝试使用DOM创建错误显示 const errorDiv = document.createElement('div'); errorDiv.style.position = 'fixed'; errorDiv.style.top = '0'; errorDiv.style.left = '0'; errorDiv.style.width = '100%'; errorDiv.style.height = '100%'; errorDiv.style.backgroundColor = 'black'; errorDiv.style.color = 'white'; errorDiv.style.display = 'flex'; errorDiv.style.justifyContent = 'center'; errorDiv.style.alignItems = 'center'; errorDiv.style.zIndex = '9999'; errorDiv.style.fontFamily = 'Arial, sans-serif'; errorDiv.style.fontSize = '24px'; errorDiv.style.textAlign = 'center'; errorDiv.style.whiteSpace = 'pre-line'; errorDiv.textContent = message; document.body.appendChild(errorDiv); } catch (domError) { console.error('[Fallback] Failed to create error display:', domError); } } // ====== SDK 加载器 ====== async function loadGravityEngineSDK() { const sdkPaths = [ 'src/assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js', 'assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js', 'lib/gravityengine.mg.cocoscreator.min.js' // 额外后备路径 ]; let sdkLoaded = false; for (const path of sdkPaths) { try { console.log(`[SDK] Attempting to load from: ${path}`); await new Promise((resolve, reject) => { if (cc && cc.assetManager && cc.assetManager.loadScript) { cc.assetManager.loadScript(path, (err) => { if (err) { console.warn(`[SDK] Load failed: ${err.message}`); reject(err); } else { resolve(); } }); } else { console.warn('[SDK] cc.assetManager not available'); reject('Asset manager not available'); } }); console.log('[SDK] GravityEngine loaded successfully'); sdkLoaded = true; initGravityEngine(); break; } catch (err) { // 继续尝试下一个路径 } } if (!sdkLoaded) { console.error('[SDK] All load attempts failed'); handleSDKLoadFailure(); } } function initGravityEngine() { if (typeof GravityEngine === 'undefined') { console.error('[SDK] GravityEngine not defined after loading'); return; } try { GravityEngine.init({ appId: 'YOUR_APP_ID', // 替换为实际AppID enableLog: true }); console.log('[SDK] GravityEngine initialized'); } catch (e) { console.error('[SDK] Initialization failed:', e); } } function handleSDKLoadFailure() { console.warn('[SDK] Disabling analytics features'); // 创建空函数降级 window.trackEvent = window.trackEvent || function() {}; window.GravityEngine = window.GravityEngine || { init: () => console.warn('SDK not available'), trackEvent: () => {} }; } // ====== 场景加载器 ====== async function loadStartScene() { try { // 尝试加载主资源包 await new Promise((resolve, reject) => { if (cc && cc.assetManager && cc.assetManager.loadBundle) { cc.assetManager.loadBundle('main', (err) => { if (err) { console.error('[Scene] Bundle load failed:', err); reject(err); } else { console.log('[Scene] Main bundle loaded'); resolve(); } }); } else { console.warn('[Scene] Asset manager not available, skipping bundle load'); resolve(); // 继续执行 } }); // 加载启动场景 if (cc.director && cc.director.loadScene) { cc.director.loadScene('start'); } else { throw new Error('Director not available'); } } catch (error) { console.error('[Scene] Failed to load main bundle:', error); // 后备方案:直接加载场景 try { console.log('[Scene] Trying direct scene load'); if (cc.director && cc.director.loadScene) { cc.director.loadScene('start'); } else { throw new Error('Director not available'); } } catch (directError) { console.error('[Scene] Direct scene load failed:', directError); throw directError; // 传递给上层处理 } } } // ====== UI_Entry 组件 ====== var _decorator = cc._decorator; var _ccclass = _decorator.ccclass; var _property = _decorator.property; // 导入依赖模块 const r_Const_Common = require("Const_Common"); const r_GravityPlatform = require("GravityPlatform"); const r_YpNetMag = require("YpNetMag"); const r_EvenType = require("EvenType"); const r_PlayerDataManager = require("PlayerDataManager"); const r_ExcelLoader = require("ExcelLoader"); const r_GameDataManager = require("GameDataManager"); const r_GameGlobalVariable = require("GameGlobalVariable"); const r_UIConfig_Game = require("UIConfig_Game"); const r_UIConfig_Home = require("UIConfig_Home"); const r_BundleConfig = require("BundleConfig"); const r_GameConfig = require("GameConfig"); const r_AudioManager = require("AudioManager"); const r_EventManager = require("EventManager"); const r_HttpManager = require("HttpManager"); const r_LogManager = require("LogManager"); const r_ResLoader = require("ResLoader"); const r_UIManager = require("UIManager"); const r_UIView = require("UIView"); var def_UI_Entry = (function (_super) { __extends(def_UI_Entry, _super); function def_UI_Entry() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.progress_loading = null; _this.loginTimeoutHandler = null; return _this; } // 组件生命周期:加载 def_UI_Entry.prototype.onLoad = function () { var _this = this; EngineReady.safeAccess(function () { try { if (cc.director && cc.director.getCollisionManager) { cc.director.getCollisionManager().enabled = true; } console.log('[UI] Collision manager enabled'); _this._show(); } catch (e) { console.error('[UI] onLoad error:', e); _this.startLoadGame(); // 直接开始加载游戏 } }).catch(function (err) { console.error('[UI] Engine access error:', err); _this.startLoadGame(); }); }; // 组件生命周期:销毁 def_UI_Entry.prototype.onDestroy = function () { if (this.loginTimeoutHandler) { cc.Tween.stop(this.loginTimeoutHandler); this.loginTimeoutHandler = null; console.log('[UI] Login timeout handler cleared'); } }; // 显示UI并初始化平台SDK def_UI_Entry.prototype._show = function () { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { this.progress_loading.progress = 0; console.log('[UI] Showing UI_Entry'); // 平台特定的SDK初始化 if (cc.sys && cc.sys.isBrowser) { this.initYPSDK().catch(function (err) { console.error('[UI] YPSDK init failed:', err); _this.startLoadGame(); }); } else { this.startLoadGame(); } // 设置登录超时保护(10秒) if (cc && cc.tween) { this.loginTimeoutHandler = cc.tween(this) .delay(10) .call(function () { console.warn('[UI] Login timeout after 10s, proceeding without SDK'); _this.startLoadGame(); }) .start(); } else { console.warn('[UI] cc.tween not available, using setTimeout'); setTimeout(() => { console.warn('[UI] Login timeout after 10s, proceeding without SDK'); this.startLoadGame(); }, 10000); } return [2]; }); }); }; // 初始化游品SDK def_UI_Entry.prototype.initYPSDK = function () { return __awaiter(this, void 0, void 0, function () { var config; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: if (typeof YPSDK === 'undefined') { console.warn('[YPSDK] YPSDK not available'); return [2]; } config = { gameChannelList: { h5: { platformType: "h5", describe: "默认 H5 渠道", version: "1.0.0" }, tt: { platformType: "tt", appId: "tt09297f94961f881b02", describe: "默认 TT 渠道", version: "1.0.0" }, wx: { platformType: "wx", appId: "wx6baaaa27ab5186ff", describe: "默认 WX 渠道", version: "1.0.0" } } }; return [4, YPSDK.init(39, "https://platform-shop-dev.hanyougame.com", config)]; case 1: _a.sent(); return [4, YPSDK.login()]; case 2: _a.sent(); // 设置登录回调 if (YPSDK.setLoginCallBack) { YPSDK.setLoginCallBack(function (success) { if (success) { // 取消超时处理 if (_this.loginTimeoutHandler) { if (cc && cc.Tween && cc.Tween.stop) { cc.Tween.stop(_this.loginTimeoutHandler); } _this.loginTimeoutHandler = null; } // 初始化重力引擎 if (r_GravityPlatform.default && typeof r_GravityPlatform.default.GA_Init === 'function') { r_GravityPlatform.default.GA_Init(YPSDK.Platform.loginData.bindingId); } _this.startLoadGame(); } }); } else { console.warn('[YPSDK] setLoginCallBack not available'); } return [2]; } }); }); }; // 开始加载游戏资源 def_UI_Entry.prototype.startLoadGame = function () { var tasks = [ this._loadGameConfig.bind(this), this._loadRemoteConfig.bind(this), this._loadExcelData.bind(this), this._loadUserData.bind(this), this._loadCommonBundle.bind(this), this._loadMainBundle.bind(this) ]; this.executeTasksWithProgress(tasks, this._loadGame.bind(this)); // 微信平台特殊处理 if (cc.sys && cc.sys.platform === cc.sys.WECHAT_GAME && typeof mg !== 'undefined') { try { mg.showShareMenu({ menus: ["shareAppMessage", "shareTimeline"] }); } catch (e) { console.warn('[WeChat] Share menu setup failed:', e); } } }; // 带进度监控的任务执行器 def_UI_Entry.prototype.executeTasksWithProgress = function (tasks, finalCallback) { var _this = this; var completed = 0; var failed = 0; var executeNext = function (index) { if (index >= tasks.length) { if (failed === 0) { finalCallback(); } else { console.warn("[Tasks] Completed with " + failed + " failures"); finalCallback(); // 即使有失败也继续 } return; } tasks[index]() .then(function () { completed++; _this._setProgress(completed / tasks.length); executeNext(index + 1); }) .catch(function (err) { console.error("[Task] #" + index + " failed:", err); failed++; _this._setProgress((completed + 0.5) / tasks.length); // 部分进度 executeNext(index + 1); }); }; executeNext(0); }; // 加载Excel数据 def_UI_Entry.prototype._loadExcelData = function () { return new Promise(function (resolve, reject) { if (r_ExcelLoader && r_ExcelLoader.ExcelLoader && r_ExcelLoader.ExcelLoader.loadAll) { r_ExcelLoader.ExcelLoader.loadAll() .then(function () { console.log('[Data] Excel data loaded'); resolve(); }) .catch(function (err) { console.error('[Data] Excel load failed:', err); reject(err); }); } else { console.warn('[Data] ExcelLoader not available'); resolve(); // 非关键任务继续 } }); }; // 加载游戏配置 def_UI_Entry.prototype._loadGameConfig = function () { return __awaiter(this, void 0, void 0, function () { var jsonAsset; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!r_ResLoader || !r_ResLoader.default || !r_ResLoader.default.loadRes) { console.warn('[Config] ResLoader not available'); return [2, Promise.resolve()]; } return [4, r_ResLoader.default.loadRes("resources", "config/GameConfig", cc.JsonAsset)]; case 1: jsonAsset = _a.sent(); if (jsonAsset && r_GameConfig && r_GameConfig.default) { r_GameConfig.default.appConfig = jsonAsset.json; console.log('[Config] Game config loaded'); if (jsonAsset.decRef) { jsonAsset.decRef(); // 释放引用 } return [2, Promise.resolve()]; } else { console.error('[Config] Game config not found'); return [2, Promise.resolve()]; // 非关键错误继续 } } }); }); }; // 加载远程配置 def_UI_Entry.prototype._loadRemoteConfig = function () { return __awaiter(this, void 0, void 0, function () { var remoteUrl, remotePath, remoteConfig; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!r_GameConfig || !r_GameConfig.default || !r_GameConfig.default.appConfig || !r_GameConfig.default.appConfig.RemoteUrl) { console.warn('[Config] RemoteUrl not configured'); return [2, Promise.resolve()]; } remoteUrl = r_GameConfig.default.appConfig.RemoteUrl; remotePath = cc.path.join(remoteUrl, "ADConfig.json"); return [4, r_ResLoader.default.loadRemote(remotePath, { ext: ".json" })]; case 1: remoteConfig = _a.sent(); if (remoteConfig && remoteConfig.json && r_GravityPlatform && r_GravityPlatform.default) { r_GravityPlatform.default.videoId = remoteConfig.json.ADUnitId[0]; if (r_GameConfig && r_GameConfig.default) { r_GameConfig.default.adConfig = remoteConfig.json; } console.log('[Config] Remote config loaded'); return [2, Promise.resolve()]; } else { console.error('[Config] Remote config load failed'); return [2, Promise.resolve()]; // 非关键错误,继续执行 } } }); }); }; // 加载公共资源包 def_UI_Entry.prototype._loadCommonBundle = function () { return new Promise(function (resolve, reject) { if (!r_ResLoader || !r_ResLoader.default || !r_ResLoader.default.loadBundle) { console.warn('[Bundle] ResLoader not available'); resolve(); return; } r_ResLoader.default.loadBundle(r_BundleConfig.BundleNames.Common) .then(function (bundle) { if (bundle) { console.log('[Bundle] Common bundle loaded'); resolve(); } else { console.warn('[Bundle] Common bundle not loaded'); resolve(); // 非关键错误继续 } }) .catch(err => { console.error('[Bundle] Common bundle load failed:', err); resolve(); // 非关键错误继续 }); }); }; // 加载主游戏包 def_UI_Entry.prototype._loadMainBundle = function () { return new Promise(function (resolve, reject) { if (!r_ResLoader || !r_ResLoader.default || !r_ResLoader.default.loadBundle) { console.warn('[Bundle] ResLoader not available'); resolve(); return; } r_ResLoader.default.loadBundle(r_BundleConfig.MainGameBundle) .then(function (bundle) { if (bundle) { console.log('[Bundle] Main game bundle loaded'); resolve(); } else { console.warn('[Bundle] Main game bundle not loaded'); resolve(); // 非关键错误继续 } }) .catch(err => { console.error('[Bundle] Main game bundle load failed:', err); resolve(); // 非关键错误继续 }); }); }; // 加载用户数据 def_UI_Entry.prototype._loadUserData = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { try { if (r_AudioManager && r_AudioManager.AudioMgr && r_AudioManager.AudioMgr.init) { r_AudioManager.AudioMgr.init(); } if (r_GameGlobalVariable && r_GameGlobalVariable.GameGlobalVariable && r_GameGlobalVariable.GameGlobalVariable.initPeiZhi) { r_GameGlobalVariable.GameGlobalVariable.initPeiZhi(); } if (YPSDK && YPSDK.Common && YPSDK.Common.curChannelData && r_YpNetMag && r_YpNetMag.YpNetMag && r_YpNetMag.YpNetMag.failSever) { var platformType = YPSDK.Common.curChannelData.platformType; if (platformType === YPSDK.GamePlatformType.WX || platformType === YPSDK.GamePlatformType.TT) { r_YpNetMag.YpNetMag.failSever(function () { if (r_YpNetMag.YpNetMag) { r_YpNetMag.YpNetMag.isFail = true; } console.warn('[Network] Server connection failed'); }); } } if (YPSDK && YPSDK.Platform && YPSDK.Platform.loginData && r_YpNetMag && r_YpNetMag.YpNetMag && r_YpNetMag.YpNetMag.initServer) { return [2, r_YpNetMag.YpNetMag.initServer(YPSDK.Platform.loginData)]; } else { console.warn('[User] No login data, skipping user init'); return [2, Promise.resolve()]; } } catch (err) { console.error('[User] Load user data failed:', err); return [2, Promise.resolve()]; // 非关键错误 } return [2]; }); }); }; // 初始化游戏主逻辑 def_UI_Entry.prototype._loadGame = function () { try { // 安全访问玩家数据管理器 if (!r_PlayerDataManager || !r_PlayerDataManager.PlayerDataMgr) { throw new Error('PlayerDataManager not available'); } // 获取引导状态 var guideIndex = r_PlayerDataManager.PlayerDataMgr.GetGuideIndexByTaskName(r_Const_Common.GuideName.战斗背包); if (guideIndex !== r_Const_Common.GameBagGuideIndex.引导完结) { // 新玩家流程 if (r_PlayerDataManager.PlayerDataMgr.GMSetGuideIndex) { r_PlayerDataManager.PlayerDataMgr.GMSetGuideIndex( r_Const_Common.GuideName.战斗背包, r_Const_Common.GameBagGuideIndex.引导初始1 ); } if (r_GameDataManager && r_GameDataManager.GameDataMgr && r_GameDataManager.GameDataMgr.ClearGameBagData) { r_GameDataManager.GameDataMgr.ClearGameBagData(); } if (r_GameGlobalVariable && r_GameGlobalVariable.GameGlobalVariable) { r_GameGlobalVariable.GameGlobalVariable.nowlevel = 1; } // 打开游戏场景 if (r_UIManager && r_UIManager.default && r_UIManager.default.open) { r_UIManager.default.open( r_BundleConfig.BundleNames.Game, r_UIConfig_Game.UIView_Game.UI_GameView ); } else { console.warn('[Game] UIManager not available, loading start scene'); cc.director.loadScene('start'); } } else { // 老玩家流程 if (r_EventManager && r_EventManager.EventMgr && r_EventManager.EventMgr.dispatchEvent) { r_EventManager.EventMgr.dispatchEvent(r_EvenType.EVENT_TYPE.Game_Load_View, true); } if (r_UIManager && r_UIManager.default && r_UIManager.default.open) { r_UIManager.default.open( r_BundleConfig.BundleNames.Home, r_UIConfig_Home.UIView_Home.UI_Hall ); } else { console.warn('[Game] UIManager not available, loading start scene'); cc.director.loadScene('start'); } } // 初始化白名单 this.onInitWhiteName(); } catch (error) { console.error('[Game] Load game failed:', error); // 尝试直接进入游戏场景 try { if (cc.director && cc.director.loadScene) { cc.director.loadScene('start'); } } catch (sceneError) { console.error('[Game] Fallback scene load failed:', sceneError); } } }; // 初始化白名单 def_UI_Entry.prototype.onInitWhiteName = function () { return __awaiter(this, void 0, void 0, function () { var url; return __generator(this, function (_a) { try { if (!YPSDK || !YPSDK.Platform || !YPSDK.Platform.loginData || !YPSDK.platformUrl) { console.warn('[WhiteList] YPSDK not initialized, skipping'); return [2]; } url = YPSDK.platformUrl + "/User/GetCfgData?userId=" + YPSDK.Platform.loginData.userUid + "&keyId=NoVideo"; console.log('[WhiteList] Checking:', url); if (r_HttpManager && r_HttpManager.HttpMgr && r_HttpManager.HttpMgr.requestData) { r_HttpManager.HttpMgr.requestData(function (response) { if (response && response.data && response.data.keyData === "true" && r_PlayerDataManager && r_PlayerDataManager.PlayerDataMgr) { r_PlayerDataManager.PlayerDataMgr.WHITE_NAME_NO_VIDEO = true; console.log('[WhiteList] User is in white list'); } }, url); } else { console.warn('[WhiteList] HttpManager not available'); } } catch (err) { console.error('[WhiteList] Init failed:', err); } return [2]; }); }); }; // 设置进度条 def_UI_Entry.prototype._setProgress = function (progress) { if (!this.progress_loading || !this.progress_loading.progress) { return; } progress = Math.max(0, Math.min(1, progress)); this.progress_loading.progress = progress; }; // 属性装饰器 __decorate([ _property(cc.ProgressBar) ], def_UI_Entry.prototype, "progress_loading", void 0); // 类装饰器 def_UI_Entry = __decorate([ _ccclass ], def_UI_Entry); return def_UI_Entry; }(r_UIView.default)); exports.default = def_UI_Entry; // ====== 启动游戏 ====== if (cc && cc.game && cc.game.run) { cc.game.run(gameMainEntry); } else { console.error('[Main] cc.game.run not available, using fallback start'); setTimeout(gameMainEntry, 1000); } 这是我的代码 你根据前面的情况给我整体修改一下,最后给我完整的代码方便我进行复制
07-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值