Phaser.js 在 forEach 循环期间删除组中的对象
Phaser.js delete object in group during forEach loop
我想在对象超过某个 x 值后销毁它。
这些对象是称为球的移相器组的一部分。
在我的更新循环中,我有这行代码:
balls.forEach(updateBalls, null, true);
这是 updateBalls 函数:
function updateBalls(ball) {
if (ball.x > 800) {
ball.destroy();
}
}
问题是在循环中删除对象打乱了循环,这是我得到的错误:
TypeError: this.children[i] is undefined
我尝试将每个球推入一个数组,然后像这样销毁每个球。
function updateBalls(ball) {
if (ball.x > 800) {
ballsToDestroy.push(ball);
}
}
然后在更新循环中:
balls.forEach(updateBalls, null, true);
for (x = 0; x < ballsToDestroy.length; balls++) {
ballsToDestroy[x].destroy();
}
虽然这给了我一些奇怪的错误。
如果我使用 ball.kill() 它会起作用,但这最终会使游戏延迟,因为球实际上并没有被移除。
我该如何解决这个问题?
听起来像是 Phaser 中的一个愚蠢错误,如果在迭代期间对组中的一个对象调用 destroy
时 Group#forEach
失败。
根据 Phaser 文档,一个组有一个 filter
function returning an ArraySet
。所以你可以获得 ArraySet
个球来销毁:
var toDestroy = balls.filter(function(ball) { return ball.x <= 800; });
然后 ArraySet
说它有一个方便的 callAll
函数,可以让我们在所有条目上调用一个函数。所以我们可以用它来摧毁它们:
toDestroy.callAll('destroy');
一应俱全:
balls.filter(function(ball) { return ball.x <= 800; }).callAll('destroy');
或使用 ES2015+
balls.filter(ball => ball.x <= 800).callAll('destroy');
( =>
和 <=
紧靠在一起看起来很有趣,但是别担心,第一个引入了箭头函数,第二个是 less-than-or-equal 运算符。)
我想在对象超过某个 x 值后销毁它。 这些对象是称为球的移相器组的一部分。 在我的更新循环中,我有这行代码:
balls.forEach(updateBalls, null, true);
这是 updateBalls 函数:
function updateBalls(ball) {
if (ball.x > 800) {
ball.destroy();
}
}
问题是在循环中删除对象打乱了循环,这是我得到的错误:
TypeError: this.children[i] is undefined
我尝试将每个球推入一个数组,然后像这样销毁每个球。
function updateBalls(ball) {
if (ball.x > 800) {
ballsToDestroy.push(ball);
}
}
然后在更新循环中:
balls.forEach(updateBalls, null, true);
for (x = 0; x < ballsToDestroy.length; balls++) {
ballsToDestroy[x].destroy();
}
虽然这给了我一些奇怪的错误。
如果我使用 ball.kill() 它会起作用,但这最终会使游戏延迟,因为球实际上并没有被移除。
我该如何解决这个问题?
听起来像是 Phaser 中的一个愚蠢错误,如果在迭代期间对组中的一个对象调用 destroy
时 Group#forEach
失败。
根据 Phaser 文档,一个组有一个 filter
function returning an ArraySet
。所以你可以获得 ArraySet
个球来销毁:
var toDestroy = balls.filter(function(ball) { return ball.x <= 800; });
然后 ArraySet
说它有一个方便的 callAll
函数,可以让我们在所有条目上调用一个函数。所以我们可以用它来摧毁它们:
toDestroy.callAll('destroy');
一应俱全:
balls.filter(function(ball) { return ball.x <= 800; }).callAll('destroy');
或使用 ES2015+
balls.filter(ball => ball.x <= 800).callAll('destroy');
( =>
和 <=
紧靠在一起看起来很有趣,但是别担心,第一个引入了箭头函数,第二个是 less-than-or-equal 运算符。)