让我们的球从墙壁反弹的最简单方法是告诉框架,我们将 <canvas>
元素的边界视为墙壁,不允许球越过它们。在 Phaser 中,这可以通过 `setCollideWorldBounds()` 方法轻松实现。将此行添加到现有的 `this.ball.body.setVelocity()` 方法调用之后。
this.ball.body.setCollideWorldBounds(true, 1, 1);
第一个 `true` 参数告诉 Phaser 启用与世界边界的碰撞检测,而后面的两个 `1` 分别是 x 轴和 y 轴的弹力系数。这意味着当球碰到墙壁时,它会以撞击前的速度反弹回来。尝试再次重新加载 index.html — 现在您应该能看到球在所有墙壁之间反弹,并在画布区域内移动。
这是您到目前为止应该看到的效果,实时运行。要查看其源代码,请单击“播放”按钮。
<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;
preload() {
this.load.setBaseURL(
"https://mdn.github.io/shared-assets/images/examples/2D_breakout_game_Phaser",
);
this.load.image("ball", "ball.png");
}
create() {
this.ball = this.add.sprite(50, 50, "ball");
this.physics.add.existing(this.ball);
this.ball.body.setVelocity(150, 150);
this.ball.body.setCollideWorldBounds(true, 1, 1);
}
update() {}
}
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);
现在这看起来有点像个游戏了,但我们还无法控制它——是时候引入 玩家挡板和控制 了。