在Phaser中摧毁精灵

时间:2014-07-05 20:37:05

标签: javascript html5 sprite phaser-framework

我在Phaser中摧毁精灵时遇到了麻烦。

我有一个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()有何不同?

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

1 个答案:

答案 0 :(得分:1)

@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 destroy方法只从对象中删除了Phaser特定的属性。 JS is in charge of generic object Garbage Collection。该对象正在逃避,因为您在范围内仍然有有效的引用。

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

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