为什么我的碰撞检测在 Phaser 中不起作用?

Why isn't my collision detection working in Phaser?

为简单起见,我有一个游戏,我试图让我的车撞到墙上。我已经尝试搜索,我已经尝试了几种方法,如下所示,我不确定为什么我无法让它工作。

这是我的 create 函数中的代码:

    create: function () {
        game.physics.startSystem(Phaser.Physics.ARCADE);

        this.carSprite = game.add.sprite(game.world.centerX, game.world.centerY, 'car');
        game.physics.arcade.enable(this.carSprite);
    this.timer = game.time.events.loop(300,
        this.addRoad, this);
    }

然后在我的 update 函数中:

    update: function () {
        game.physics.arcade.overlap(this.carSprite, this.wallSprite, this.scoring, null, this);
}

我正在这样创建 wallSprite

 addOneRoadSection: function (x, y) {
this.scoreCalculator += 1;
        if (this.scoreCalculator == 10) {
            this.scoreCalculator = 0;

            this.wallSprite = game.add.sprite(x + 100, y, 'wall');
            game.physics.arcade.enable(this.wallSprite);
            this.wallAnimation = this.wallSprite .animations.add('wallAnimation');
            this.wallSprite.animations.play('wallAnimation', 30, true);
            this.wallSprite.body.velocity.y = 100;
            this.wallSprite.checkWorldBounds = true;
            this.wallSprite.outOfBoundsKill = true;
        }
}

我这样打电话给addOneRoadSection

    addRoad: function () {
        this.addOneRoadSection(this.xValue, 0);
}

addRoad 正在 create 中使用 this.timer 调用。

总之,当 scoreCalculator 为 10 时,它添加了一堵墙。这很好用,墙动画很好,但碰撞检测根本不起作用。

我尝试将 if 语句中的代码移动到我的 create 函数中,它在碰撞检测方面运行良好(但其他东西会损坏,所以我不能将其保留在那里)。我究竟做错了什么?我怀疑因为我平均每秒调用一次 this.wallSprite 它被添加为 this.wallSprite 的新精灵覆盖但我不完全确定我还有什么办法应该这样做吗?

所以我想通了。发生的事情是,我最初倾向于创建一个新精灵,而改写另一个精灵是正确的。

以下是我解决问题的方法:

create中:

create: function(){ 
 //Create a wallSprite array
 var wallSprite = [];
}

现在我在 addOneRoadSection 中添加新的 wallSprite 时有了一个数组,我可以像这样向每个精灵添加物理:

   addOneRoadSection: function (x, y) {

            this.wallSprite.push(game.add.sprite(x + 100, y, 'wall'));
            game.physics.arcade.enable(this.wallSprite[this.wallSprite.length -1]);
            this.wallAnimation = this.wallSprite[this.wallSprite.length - 1].animations.add('wallAnimation');
            this.wallSprite[this.wallSprite.length - 1].animations.play('wallAnimation', 30, true);
            this.wallSprite[this.wallSprite.length -1].body.velocity.y = 100;
            this.wallSprite[this.wallSprite.length - 1].checkWorldBounds = true;
            this.wallSprite[this.wallSprite.length -1].outOfBoundsKill = true;
}

终于在 update 我只需要这样做:

    for (var i = 0; i < this.wallSprite.length; i++) {
        game.physics.arcade.overlap(this.car, this.wallSprite, this.scoring, null, this);
    }

瞧 - 碰撞检测现在适用于每个精灵。