讓我們的球從牆壁反彈的最簡單方法是告訴框架,我們將 <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);
現在這看起來有點像個遊戲了,但我們還無法控制它——是時候引入 玩家擋板和控制 了。