Javascript phaser.io如何在全球范围内使用国有独立资产
切换到状态Javascript phaser.io如何在全球范围内使用国有独立资产,javascript,caching,html5-canvas,ecmascript-5,phaser-framework,Javascript,Caching,Html5 Canvas,Ecmascript 5,Phaser Framework,切换到状态b(其中phaserGameInstance是Phaser.Game的一个实例)后,我想将状态a中预加载的图像/精灵添加到phaserGameInstance.world中 由于所有资产都全局存储在浏览器缓存和phaserGameInstance.cache中,因此它们应该在所有状态下都可用,但实际上并非如此 我发现的解决方法是使用statea缓存对象的属性扩展stateb缓存对象,这有点令人不安,可能不是预期的方式: var priorCache = phaserGameInstan
b
(其中phaserGameInstance
是Phaser.Game
的一个实例)后,我想将状态a
中预加载的图像/精灵添加到phaserGameInstance.world
中
由于所有资产都全局存储在浏览器缓存和phaserGameInstance.cache
中,因此它们应该在所有状态下都可用,但实际上并非如此
我发现的解决方法是使用statea
缓存对象的属性扩展stateb
缓存对象,这有点令人不安,可能不是预期的方式:
var priorCache = phaserGameInstance.state.getCurrentState().cache; // State 'a'
phaserGameInstance.state.start('b'); // Switch to state 'b'
jQuery.extend( // Merges the cache of state 'a' recursively
true, // into the cache of the current state 'b'
phaserGameInstance.state.getCurrentState().cache,
priorCache
);
我还没有测试在状态b
中预加载资产时这是否有效(合并过程可能会覆盖状态b
的属性),但因为我只在状态a
中预加载我的东西一次,所以这是我当前使用的修复方法
如何独立于状态使用预加载的资产?调用
phaserGameInstance.state.start('b')
实际上不会将状态从a
切换到b
。它只是将状态b
指定为要切换到的挂起状态。这意味着它在某种程度上是一种异步方法
调用phaserGameInstance.state.start('b')
后立即将对象添加到phaserGameInstance.world
将对象添加到状态a
,而状态b
仍处于挂起状态,并将在下一次游戏更新中激活。更新发生后,phaserGameInstance.world
为空,因为当statea
关闭时,所有对象都将被删除。因此,不需要合并缓存或任何东西
以下是解决方案:
phaserGameInstance.state.add(
'b',
{
create: function () { // Add the assets loaded in state 'a' here ...
phaserGameInstance.add.image(0, 0, 'myImage');
}
}
);
phaserGameInstante.state.start('b');
// ... not here! State 'a' is still active in this line.
由于对象被添加到statea
中,看起来它们依赖于它们预加载的状态,但实际上它们是独立于状态的,正如我在问题中所假设的那样