2016-05-16 80 views
1

我正在製作一個簡單的遊戲,其中一個球對象與子彈對象碰撞。對象正確碰撞,但包含在對象的相同collides()函數中的回調function(addscore())僅被調用一次(很可能在對象的第一次創建期間)。Phaser.js遊戲對象按預期碰撞,但碰撞回調不是

以下是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。 查看源代碼以查看整個代碼。謝謝你的幫助。 :)

回答

1

我還沒有任何P2物理的經驗,所以這可能是完全錯誤的。使用街機物理時,組在create函數中初始化,但在更新函數中檢查碰撞。

所以,你必須做的就是招:

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

要在更新功能(連同碰撞檢查任何其他代碼)。

同樣,我還沒有任何p2物理系統的經驗,所以這可能是不正確的。

對不起,如果這沒有幫助。

3

看着代碼縮減你在這裏發佈一切看起來不錯的第一眼。然而,當我在gh上查看你的代碼時,我發現你沒有將addScore作爲回調函數傳遞,而只是調用它。

更改main.js線67

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

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

應該做的伎倆。

+0

本帖子中的第67行已更改爲您建議的行。我忘了在gh頁面上推送更新的代碼。對於那個很抱歉。無論如何,問題仍然存在,儘管addscore函數並沒有被調用。我現在上傳了最新的代碼,現在可以再試一次。 – bhounter