为了提供失败机制,我们将禁用球与屏幕底部边缘的碰撞。将以下代码添加到 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);
现在基础的游戏玩法已经就绪,让我们通过引入可摧毁的砖块来让游戏更有趣——是时候 构建砖块区域 了。