還記得 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 的 物理引擎並進行一些設定工作。