Phaser.js游戏对象按预期发生碰撞,但碰撞回调则不然

时间:2016-05-16 07:41:39

标签: javascript collision-detection phaser-framework

我正在制作一个简单的游戏,其中一个球对象与子弹对象一起击中。对象正常碰撞,但回调function(addscore())包含在对象的相同collides()函数中,只被调用一次(最有可能在对象的第一次创建期间)。

以下是create()功能的代码段。碰撞部分位于底部:

create: function() { 

        this.cursors = this.game.input.keyboard.createCursorKeys();

        //background
        this.cloud = game.add.sprite(50, 100, 'cloud');
        this.cloud.scale.setTo(.4,.4);
        this.cloud1 = game.add.sprite(250, 200, 'cloud');
        this.cloud1.scale.setTo(.5,.5);
        this.grass = game.add.sprite(0, 470, 'grass');
        game.stage.backgroundColor = '#71c5cf';

        //Ball and cannon
        game.physics.startSystem(Phaser.Physics.P2JS);
        game.physics.p2.restitution = .9;
        this.ball = game.add.sprite(200, 245, 'ball');
        this.cannon = game.add.sprite(200, 490, 'cannon');
        this.ball.anchor.setTo(0.4, 0.4);
        this.cannon.anchor.setTo(0.5, 0.5);
        this.cannon.scale.setTo(.4,.4);
        this.ball.scale.setTo(.4,.4);
        game.physics.p2.enable(this.ball);
        this.ball.body.setCircle(29);
        this.game.debug.body(this.ball)
        //gravity and bounce, collision
        this.game.physics.p2.gravity.y = 1500; 

        this.ballCollisionGroup = this.game.physics.p2.createCollisionGroup();
        this.bulletCollisionGroup = this.game.physics.p2.createCollisionGroup();
        this.game.physics.p2.updateBoundsCollisionGroup();
        this.ball.body.setCollisionGroup(this.ballCollisionGroup);
        this.ball.body.collides([this.bulletCollisionGroup], this.addscore);

        this.bullet = game.add.group();

        this.bullet.createMultiple(20, 'bullet');

        this.bullet.callAll('events.onOutOfBounds.add', 'events.onOutOfBounds', this.resetbullet);
        this.bullet.callAll('anchor.setTo', 'anchor', 0.1, 0.1);
        this.bullet.callAll('scale.setTo', 'scale', .1, .1);
        this.bullet.setAll('checkWorldBounds', true);
        this.bullet.enableBody = true;
        this.bullet.physicsBodyType = Phaser.Physics.P2JS;
        game.physics.p2.enable(this.bullet);


        this.bullet.forEach(function(child){
        child.body.setCircle(7);
        child.body.setCollisionGroup(this.bulletCollisionGroup);
        child.body.collides([this.ballCollisionGroup]);
        child.body.collideWorldBounds=false;
    }, this);
    },

您可以在此处查看游戏:http://gabrnavarro.github.io/Volleyball.js。 查看源代码以查看整个代码。谢谢你的帮助。 :)

2 个答案:

答案 0 :(得分:3)

看着代码剪断你发布在这里,一切看起来都很好看。但是,当我查看你的代码时,我发现你没有将addScore作为回调传递,而只是调用它。

更改main.js第67行

this.ball.body.collides([this.bulletCollisionGroup], this.addscore(), this);

this.ball.body.collides([this.bulletCollisionGroup], this.addscore, this);

应该做的伎俩。

答案 1 :(得分:1)

我对P2物理没有任何经验,所以这可能是完全错误的。使用街机物理时,会在创建函数中初始化组,但会在更新函数中检查碰撞。

所以你需要做的就是搬家:

    this.ball.body.collides([this.bulletCollisionGroup], this.addscore, this);

更新功能(以及检查碰撞的任何其他代码)。

同样,我对p2物理系统没有任何经验,所以这可能是不正确的。

很抱歉,如果这没有帮助。