為了提供失敗機制,我們將停用球與螢幕底部邊緣的碰撞。將以下程式碼新增到 create() 方法中,放在最上面:
this.physics.world.checkCollision.down = false;
這將使三個邊界(頂部、左側和右側)反彈球,但第四個邊界(底部)將消失,讓球在擋板錯過時掉出螢幕。我們需要一種方法來檢測這種情況並採取相應行動。在 update() 方法的末尾新增以下行:
const ballIsOutOfBounds = !Phaser.Geom.Rectangle.Overlaps(
this.physics.world.bounds,
this.ball.getBounds(),
);
if (ballIsOutOfBounds) {
// Game over logic
alert("Game over!");
location.reload();
}
新增這些行後,將檢查球是否超出了世界(在本例中是畫布)的邊界,然後顯示一個警告框。當你點擊出現的警告框時,頁面將重新載入,讓你重新開始遊戲。
注意:這裡的使用者體驗非常粗糙,因為 alert() 顯示一個系統對話方塊並阻塞了遊戲。在一個真正的遊戲中,你可能希望使用 <dialog> 設計自己的模態對話方塊。
此外,我們稍後還會新增一個 “開始”按鈕,但在這裡,遊戲會在頁面載入時立即開始,所以你可能在開始玩遊戲之前就“輸了”。為了避免煩人的對話方塊,我們將暫時移除 alert() 呼叫。
這是您到目前為止應該看到的效果,即時執行。要檢視其原始碼,請單擊“播放”按鈕。
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.js"></script>
* {
padding: 0;
margin: 0;
}
class ExampleScene extends Phaser.Scene {
ball;
paddle;
preload() {
this.load.setBaseURL(
"https://mdn.github.io/shared-assets/images/examples/2D_breakout_game_Phaser",
);
this.load.image("ball", "ball.png");
this.load.image("paddle", "paddle.png");
}
create() {
this.physics.world.checkCollision.down = false;
this.ball = this.add.sprite(
this.scale.width * 0.5,
this.scale.height - 25,
"ball",
);
this.physics.add.existing(this.ball);
this.ball.body.setVelocity(150, -150);
this.ball.body.setCollideWorldBounds(true, 1, 1);
this.ball.body.setBounce(1);
this.paddle = this.add.sprite(
this.scale.width * 0.5,
this.scale.height - 5,
"paddle",
);
this.paddle.setOrigin(0.5, 1);
this.physics.add.existing(this.paddle);
this.paddle.body.setImmovable(true);
}
update() {
this.physics.collide(this.ball, this.paddle);
this.paddle.x = this.input.x || this.scale.width * 0.5;
const ballIsOutOfBounds = !Phaser.Geom.Rectangle.Overlaps(
this.physics.world.bounds,
this.ball.getBounds(),
);
if (ballIsOutOfBounds) {
// Game over logic
location.reload();
}
}
}
const config = {
type: Phaser.CANVAS,
width: 480,
height: 320,
scene: ExampleScene,
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
},
backgroundColor: "#eeeeee",
physics: {
default: "arcade",
},
};
const game = new Phaser.Game(config);
現在基礎的遊戲玩法已經就緒,讓我們透過引入可摧毀的磚塊來讓遊戲更有趣——是時候 構建磚塊區域 了。