无法在我自己的函数中创建精灵

Can't create sprite inside my own function

正在尝试使用 .time.addEvent 定期生成目标。但是回调函数不会生成精灵。控制台吐出 TypeError: this.add is undefined (我创建的 spawnTarget 函数中的那个)。我已将精灵放置在 spawnTarget 函数之外,它工作正常!

export class StandarModeScene extends Phaser.Scene {

constructor() {
    super('standarMode_scene');
}

preload() {
    this.load.image('target', '../assets/target1.png');
}

create() {
    this.cameras.main.setBackgroundColor('#302e2d'); //setting the background to grey
    let target = this.add.sprite(Phaser.Math.Between(0, 600), Phaser.Math.Between(0, 800), 'target'); //add sprite

    let targetSpawnInterval = 350;

    function spawnTarget() {
       this.add.sprite(Phaser.Math.Between(0, 600), Phaser.Math.Between(0, 800), 'target');
    }

    this.time.addEvent({
        delay: targetSpawnInterval,
        callback: spawnTarget,
        loop: true
    });

}

我也试过了

function spawnTarget() {
    target.add.sprite(Phaser.Math.Between(0, 600), Phaser.Math.Between(0, 800), 'target');
}

但是 TypeError 显示 target.add 未定义。

听起来您 运行 遇到了 'this' 范围问题。查看 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this 了解更多信息。

作为解决方案,我认为将 'spawnTarget' 函数声明移到 'create' 函数之外是最简单的方法。或者您可以使用 call/apply.

将 this 上下文传递给您的函数

这不会保留在 spawnTarget 函数中。 尝试使用 bind 函数:

this.time.addEvent({
    delay: targetSpawnInterval,
    callback: spawnTarget.bind(this),
    loop: true
});