【问题标题】:Destroying sprites in Phaser在 Phaser 中销毁精灵
【发布时间】:2014-08-26 17:48:20
【问题描述】:

我无法在 Phaser 中销毁 Sprite。

我有一个 JavaScript 对象,我们称之为 Block。 Block 有一个 sprite 属性,设置如下:

this.sprite = this.game.add.sprite(this.x, this.y, 'blocks', this.color);

在我的代码中,Block 被两个不同的数组引用:

square[0] = Block;
destroy[0] = Block;

在某个 Update() 循环中,我需要销毁精灵,所以我使用以下代码:

square[0].sprite.destroy(true); //Destroy the sprite.
square[0] = null; //Remove the reference.

在下一个 Update() 循环中,当我查看 destroy[0] 时,我希望看到:

destroy[0].sprite: null

但是我看到的是:

destroy[0].sprite: b.Sprite

属性只是默认设置并设置为 false。我担心的是,如果我现在将 destroy[0] 设置为 null,那个 sprite 对象会发生什么?

它会漂浮还是会自动清理? 我应该先以某种方式破坏 Block 对象吗? 另外,如果destroy() 没有清空引用,它与kill() 有什么不同?

对此事的任何想法将不胜感激。

【问题讨论】:

  • 如果没有引用,垃圾收集器会清理它。
  • 如果你找到了你要找的东西,请接受答案。

标签: javascript html sprite phaser-framework


【解决方案1】:

杀戮与毁灭的区别

Kill 应该停止渲染,但对象仍然存在。如果您想制作可重用的对象,那就太好了。 您可以再次创建对象,而无需再次实际创建对象。

Destroy 应该删除对象以及与之相关的所有内容。当您想将对象发送到垃圾收集器时,您可以使用它。

请注意,对于文本等某些对象,不能使用kill,只能使用destroy

参考: http://www.html5gamedevs.com/topic/1721-how-to-remove-text/#entry12347

【讨论】:

    【解决方案2】:

    @ibnu 是正确的。 Destroy 核对对象,而kill 停止渲染。但是,您的问题与内存泄漏和 GC 有关。我不是 GC 专业人士,但这是我认为正在发生的事情。

    //create an object
    this.sprite = this.game.add.sprite(this.x, this.y, 'blocks', this.color);
    //create additional references to the object
    square[0] = Block;
    destroy[0] = Block;
    //destroy the object via Phaser's call. Remove 1/2 reference
    square[0].sprite.destroy(true); //Destroy the sprite.
    square[0] = null; //Remove the reference.
    

    但是destroy[0].sprite 仍然包含对您“被破坏”的精灵的引用。 this.sprite 可能也是。这是因为 Phaser 销毁方法仅从对象中删除 Phaser 特定属性。 JS is in charge of generic object Garbage Collection。该对象正在转义,因为您在范围内仍然有有效的引用。

    通过从范围destroy[0].sprite = null 中删除引用或等待下一个状态更改范围来解决此问题(假设destroy 不是静态变量)。您不必自己管理内存资源,JS != C。只要确保您不要 leak 跨不同范围的变量即可。

    What is JavaScript garbage collection?(虽然我认为delete命令不再推荐用于GC,但在Phaser中肯定没有必要)

    【讨论】:

      猜你喜欢
      • 2018-05-27
      • 1970-01-01
      • 2017-05-27
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多