移相器.io如何在全局范围内使用独立于国家的资产

phaser.io How to use state independent assets globally

本文关键字:于国家 独立 国家 io 范围内 全局      更新时间:2023-09-26

我想在切换到状态b(其中phaserGameInstancePhaser.Game的实例)后将状态a预加载的图像/精灵添加到phaserGameInstance.world中。

由于所有资源都是全局存储在浏览器缓存和phaserGameInstance.cache中,它们应该在所有状态下可用,但实际上不是。

我找到的解决方法是用状态a的缓存对象的属性扩展状态b的缓存对象,这有点令人不安,可能不是预期的方式:

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为空,因为当状态a关闭时,所有对象将被删除。因此,不需要合并缓存或其他任何东西。

解决方案如下:

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.

由于对象被添加到状态a中,似乎它们会依赖于它们已预加载的状态,但实际上它们是状态独立的,正如我的问题所假定的。