使用 Cocos2d-html5,是否有任何方法可以“退出”引擎并重新初始化其状态,以便稍后重新启动引擎。我们在单页网络应用程序中使用 Cocos2d 游戏。如果用户导航到另一个页面,我们希望以编程方式移除画布 div 并尝试退出 Cocos2d 引擎。不幸的是,似乎没有好的方法可以做到这一点,并且尝试加载新游戏会导致错误。
如何干净地卸载场景并退出引擎?
我们正在使用 V3.1 并尝试了几种方法,它们似乎都不起作用。例如:
- 试图重置 cc 对象中保存的许多变量(详情如下)。这种方法迫使您重置看起来私有的变量,因为它们以 _ 开头并且不在文档中。
- 挑选、选择和重写一些 CCBoot.js,但这对于引擎更新来说似乎很复杂并且不可持续,因为它在整个库中都依赖于它。
我想到的其他方法,但听起来都像 hack:
3. 清空整个 cc 对象并以某种方式再次运行脚本,但这可能意味着剥离脚本标签或模块并再次添加并运行它。
4. 将 cc 对象包裹在另一个对象中,这样更容易重置。CCBoot.js 看起来可能会将一些东西附加到窗口对象。
我用第一种方法走得最远,但我被上下文问题困住了。离开画布时,在将其从 DOM 中删除之前,我将其称为:
// Remove anything that might possibly keep a reference to the old context
cc.textureCache.removeAllTextures();
cc._drawingUtil = null;
cc.stencilBits = null;
// Purge the cc.director, schedules, event listeners, running scene, animations, cached data.
cc.director.purgeDirector();
// Remove references to the context
cc._renderContext = null;
cc.webglContext = null;
window.gl = null;
cc._mainRenderContextBackup = null;
// Remove reference to DOM elements
cc._canvas = null;
cc.container = null;
cc._gameDiv = null;
// Reset CCBoot variables that might stop us from re-initialising
cc._rendererInitialized = false;
cc._setupCalled = false;
cc._renderType = -1;
然后当我们在第二次或后续时间调用时重新启动
// Reset all system and flag variables
cc._initSys(cc.game.config, cc.game.CONFIG_KEY);
cc.game.run();
这是我得到的错误类型。看起来它没有正确重置上下文:
WebGL: INVALID_OPERATION: bindTexture: object not from this context
WebGL: INVALID_OPERATION: texImage2D: no texture
WebGL: INVALID_OPERATION: uniformMatrix4fv: location is not from current program
WebGL: INVALID_OPERATION: vertexAttribPointer: no bound ARRAY_BUFFER