如何为使用 Phaser 中的构造函数创建的动态生成的精灵启用碰撞?

How to enable collision for dynamically generated sprites created using a constructor in Phaser?

代码是这样的:

  function RainDrops(charLabel){
  this.xLocArray = [50, 120, 190, 260]; //Array for x pos 
  this.charLabel = charLabel;
  this.rainCreator = function(){
                                var x = Math.floor(Math.random()*4);
                                this.genChar = game.add.sprite(this.xLocArray[x], 0, charLabel);
                                game.physics.arcade.enable(genChar);
                                genChar.body.gravity.y = 50;
                                genChar.body.collideWorldBounds = true;
                                };


}

function createChar(){
    var randomIndex = Math.floor(Math.random()*3);
    switch(randomIndex){
        case 0:
            var Apple = new RainDrops('apple',uniqueRainDropId);
            Apple.rainCreator();
            break;
        case 1:
            var Candy = new RainDrops('candy',uniqueRainDropId);
            Candy.rainCreator();
            break;
        case 2:
            var Duck = new RainDrops('duck',uniqueRainDropId);
            Duck.rainCreator();
            break;
    }
}

function create(){
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.add.sprite(0, 0, 'backyard');
    var ground = game.add.sprite(40, game.world.height - 300, 'ground');
    ground.scale.setTo(0.7, 0.2);
    game.physics.arcade.enable(ground);
    ground.body.immovable = true;
    game.time.events.loop(500, createChar, this);

}

function update(){
    game.physics.arcade.collide(ground, ????);
}  

我是 javaScript 和 Phaser(以及一般编程)的新手。我一直在自学 js 和相位器,但我被困在了这一点上。现在我如何告诉更新函数检查碰撞,因为精灵是动态创建的。提前致谢:)

Phaser 中的 collide function 旨在处理精灵和组。因此,您可以将雨精灵添加到 Phaser.Group,然后在碰撞调用中使用该组。像这样:

function create() {
    var raingroup = game.add.group();
    game.physics.startSystem(Phaser.Physics.ARCADE);
    // etc.

function createChar() {
    //..
    Apple.rainCreator();
    raingroup.add(Apple);
    break;
    //etc. add Candy and Duck to group in same way

function update(){
    game.physics.arcade.collide(ground, raingroup, mycollisionHandler)
}

function mycollisionHandler(grnd, rainspr) {
    // note, parameters grnd and rainspr represent the sprites that have collided
    rainspr.kill();
}

请注意,您可以选择使用 processHandler 进行额外检查并确定重叠对象是否应该发生碰撞。在你的情况下,我认为你真的不需要它,只是为了展示它是如何工作的:

game.physics.arcade.collide(ground, raingroup, mycollisionHandler, myprocessHandler, this);
//..
function myprocessHandler(grnd, rain) {
    if (rain.health > 0) {
        return false; // no collisionHandler
    } else {
        return true; // will cause a call to collisionHandler
    };
}