在我的主游戏类中,我有一个
createCar
方法,该方法动态创建一辆汽车并迭代其他汽车并映射彼此之间的光线投射(因此汽车可以检测彼此之间的距离):
createCar(scene, x, y, angle, speed, name) {
const car = new Car(scene, x, y, angle, speed);
car.name = name; // for debug
this.carsGroup.children.iterate((c) => {
c.raycaster.mapGameObjects(car, true);
car.raycaster.mapGameObjects(c, true);
});
this.carsGroup.add(car);
}
它有效,除非我想删除一辆车:
update() {
this.carsGroup.children.iterate((car) => {
// Car is out of screen
if (!this.cameras.main.worldView.contains(car.x, car.y)) {
this.carsGroup.remove(car);
this.carsGroup.children.iterate((c) => {
c.raycaster.removeMappedObjects(car);
car.raycaster.removeMappedObjects(c);
});
car.destroy();
} else {
car.update();
car.debug();
}
});
}
然后,当它在内部尝试检索“raycasterMap”并销毁它时,它会失败:
object.data.get('raycasterMap').destroy();
raycaster-core.js:396 Uncaught TypeError:无法读取未定义的属性(读取“销毁”) 在 Raycaster.removeMappedObjects (raycaster-core.js:396:48) 在 game.js:51:23
我不知道如何正确地将汽车从场景和内存中删除。 如果我只是调用
car.destroy()
其他汽车会抛出异常,因为光线投射仍然有引用。
完整的代码笔示例: https://codepen.io/vvyshko/pen/bGOxpbG
我认为问题在于清理工作不是最佳的。我建议,将清理放入
destroy
- 类的 car
函数中,然后在场景的 update
函数中添加验证,检查 car
- 子级是否是有效对象,
这里的改动:
class Car extends Phaser.Physics.Arcade.Sprite {
// ...
destroy(){
super.destroy();
// Cleanup data
this.ray.destroy();
this.raycaster.destroy();
}
// ...
}
class Example extends Phaser.Scene {
//...
update() {
this.carsGroup.children.iterate((car) => {
// Check if the list item is valid
if (!car) {
return;
}
if (!this.cameras.main.worldView.contains(car.x, car.y)) {
// Remove Car from Group and destroy Object
this.carsGroup.remove(car, true, true);
} else {
car.update();
car.debug();
}
});
}
}