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

时间:2017-04-25 01:17:14

标签: javascript html5 phaser-framework

代码如下:

  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&移相器,但我在这一点上卡住了。现在我如何告诉更新函数检查碰撞,因为动态创建了精灵。在此先感谢:)

1 个答案:

答案 0 :(得分:0)

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
    };
}