2014-09-20 57 views
6

我正在使用HTML5的PhaserJS庫開發一款新遊戲,並且遇到了我遇到的問題。我使用P2物理引擎進行基礎平臺物理學,並且無法讓世界範圍的碰撞起作用。這裏是我的代碼:如何使用PhaserJS添加基本的世界碰撞?

Game.js

function create() { 
    game.world.setBounds(0, 0, 800, 300); 
    game.physics.startSystem(Phaser.Physics.P2JS); 
    game.physics.p2.restitution = 0.8; 

    player.create(game); 
    player.instance.body.collideWorldBounds = true; 
} 

Player.js

Player.prototype.create = function(game) { 
    this.instance = game.add.sprite(100, 100, 'player'); 
    game.physics.p2.enable(this.instance, Phaser.Physics.P2JS); 

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

現在我的理解是,我需要通過調用「game.world.setBounds設置世界界限(寬度,高度)「,然後通過調用」player.instance.body.collideWorldBounds = true;「來檢查邊界,但玩家精靈仍然會穿過邊界。任何幫助是極大的讚賞。謝謝!

編輯:我使用PhaserJS 2.0.7。

回答

6

您可能要更新到Phaser 2.1.1,因爲看起來他們在那裏修復了這個問題。

您可以從this example中看到。

下面是該示例的源代碼:

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); 

function preload() { 

    game.load.image('stars', 'assets/misc/starfield.jpg'); 
    game.load.spritesheet('ship', 'assets/sprites/humstar.png', 32, 32); 

} 

var ship; 
var starfield; 
var cursors; 

function create() { 

    starfield = game.add.tileSprite(0, 0, 800, 600, 'stars'); 

    game.physics.startSystem(Phaser.Physics.P2JS); 

    game.physics.p2.restitution = 0.8; 

    ship = game.add.sprite(200, 200, 'ship'); 
    ship.scale.set(2); 
    ship.smoothed = false; 
    ship.animations.add('fly', [0,1,2,3,4,5], 10, true); 
    ship.play('fly'); 

    // Create our physics body. A circle assigned the playerCollisionGroup 
    game.physics.p2.enable(ship); 

    ship.body.setCircle(28); 

    // This boolean controls if the player should collide with the world bounds or not 
    ship.body.collideWorldBounds = true; 

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

} 

function update() { 

    ship.body.setZeroVelocity(); 

    if (cursors.left.isDown) 
    { 
     ship.body.moveLeft(200); 
    } 
    else if (cursors.right.isDown) 
    { 
     ship.body.moveRight(200); 
    } 

    if (cursors.up.isDown) 
    { 
     ship.body.moveUp(200); 
    } 
    else if (cursors.down.isDown) 
    { 
     ship.body.moveDown(200); 
    } 

} 
+0

這可能是2.0.7版本可能會導致我幾個問題,我沒有意識到一個新版本,老實說。我今晚會嘗試一下,並告訴你它是否適合我。感謝您的回答。 – hRdCoder 2014-09-23 16:13:04

+0

好的,太好了。希望這對你有用。 – GDP2 2014-09-23 17:44:30

+0

它的工作!非常感謝你@Ylluminarious。 :) – hRdCoder 2014-09-24 13:51:10

3

在我的遊戲我不得不打電話p2.setBoundsToWorld更新P2的物理邊界相匹配的世界範圍:

function create() { 
    game.world.setBounds(0, 0, 800, 300); 
    game.physics.startSystem(Phaser.Physics.P2JS); 
    game.physics.p2.setBoundsToWorld(true, true, true, true, false); 

簽名如下:

setBoundsToWorld: function (left, right, top, bottom, setCollisionGroup) 
+0

我不知道這個方法,其實。今晚我會試一試,看看我能得到什麼結果。感謝您的回答。 – hRdCoder 2014-09-23 16:11:04