还记得 update() 方法及其定义吗?其中的代码会在每一帧执行,所以这是放置更新屏幕上球位置代码的理想位置。在 update() 中添加以下新行,如下所示
class ExampleScene extends Phaser.Scene {
// ...
update() {
this.ball.x += 1;
this.ball.y += 1;
}
}
上面的代码会在每一帧将代表画布上球坐标的 x 和 y 属性各加 1。重新加载 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");
}
update() {
this.ball.x += 1;
this.ball.y += 1;
}
}
const config = {
type: Phaser.CANVAS,
width: 480,
height: 320,
scene: ExampleScene,
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
},
backgroundColor: "#eeeeee",
};
const game = new Phaser.Game(config);
下一步是添加一些基本的碰撞检测,以便我们的球可以从墙壁上反弹。这需要几行代码——比我们目前看到的要复杂得多,特别是如果我们还想添加球拍和砖块碰撞的话——但幸运的是,Phaser 允许我们比纯 JavaScript 更轻松地实现这一点。
无论如何,在做所有这些之前,我们将首先介绍 Phaser 的 物理引擎并进行一些设置工作。