全ブタを倒したらクリア
前の 02 当たったブタを消す で、ブタを消せるようになりました。 この節では、ブタを全部倒したら「クリア画面」へ進むようにします。勝ちの条件です。
今回さわる
game/:scenes/game-scene.jsを書き換え、scenes/clear-scene.jsを追加、index.htmlとmain.jsに登録
前の節を終えていない人は、ここから始められます。
残りのブタを数える
Section titled “残りのブタを数える”残りの数を覚えておきます。0 になったらクリアです。
update の書き換え(下の「倒すたびに減らし、0 でクリアへ」)も、下の差分に入っています。
scenes/game-scene.js を変更する
Section titled “scenes/game-scene.js を変更する”4545 pig.isPig = true; // 衝突したときに見分けるための目印。4646}4747
48this.pigsLeft = pigPositions.length;49this.cleared = false;50
4851// 衝突中に消すと不安定なので、ためて update でまとめて消す。4952this.pendingRemoval = new Set();145148 update() {146149 for (const pig of this.pendingRemoval) {147150 pig.destroy();151 this.pigsLeft -= 1;148152 }149153 this.pendingRemoval.clear();154
155 // 何度も遷移しないよう、クリアは1回だけ。156 if (!this.cleared && this.pigsLeft <= 0) {157 this.cleared = true;158 this.scene.start('Clear');159 }150160 }151161}this.pigsLeft… 残りのブタの数。最初は置いた数(pigPositions.length)です。this.cleared… もうクリアしたかどうかの印。クリア画面へ二重に進まないために使います。
倒すたびに減らし、0 でクリアへ
Section titled “倒すたびに減らし、0 でクリアへ”ブタを消すたびに残りを1つ減らします。0 になったらクリア画面へ進みます。
this.pigsLeft -= 1… ブタを1匹消すたびに残りを減らします。if (!this.cleared && this.pigsLeft <= 0)… まだクリアしておらず、残りが 0 になったら実行します。this.cleared = true… 印を立てて、次のフレームでもう一度クリアに進まないようにします。this.scene.start('Clear')… クリア画面へ切り替えます。
クリア画面のシーン
Section titled “クリア画面のシーン”scenes/clear-scene.js を作成する
Section titled “scenes/clear-scene.js を作成する”1class ClearScene extends Phaser.Scene {2 constructor() {3 super('Clear');4 }5
6 create() {7 this.add8 .text(360, 200, 'クリア!', {9 fontSize: '40px',10 color: '#2e7d32',11 fontStyle: 'bold',12 })13 .setOrigin(0.5);14
15 this.add16 .text(360, 280, 'クリックでスタートに戻る', {17 fontSize: '18px',18 color: '#555555',19 })20 .setOrigin(0.5);21
22 this.input.once('pointerdown', () => this.scene.start('Start'));23 }24}登録も忘れずに。作ったファイルは 2 か所に足します。
まず index.html の読み込みです。main.js より前に置きます。main.js が起動する時点で
ClearScene が用意されていないと、ClearScene is not defined で止まります。
index.html を変更する
Section titled “index.html を変更する”33<head>44 <meta charset="utf-8" />55 <meta name="viewport" content="width=device-width, initial-scale=1" />6 <title>13 当たったブタを消す</title>6 <title>14 全ブタを倒したらクリア</title>77 <style>88 body {99 margin: 0;2121 <script src="scenes/start-scene.js" defer></script>2222 <script src="scenes/game-scene.js" defer></script>2323 <script src="scenes/gameover-scene.js" defer></script>24 <script src="scenes/clear-scene.js" defer></script>2425 <script src="main.js" defer></script>2526</head>2627<body></body>つぎに main.js の scene 配列に ClearScene を加えます。
main.js を変更する
Section titled “main.js を変更する”77 default: 'matter',88 matter: { gravity: { y: 1 } },99 },10 scene: [StartScene, GameScene, GameOverScene],10 scene: [StartScene, GameScene, GameOverScene, ClearScene],1111});ブタを3匹とも倒すと「クリア!」の画面になります。鳥を撃ち切って倒しきれなければ、 これまでどおりゲームオーバーです。これで勝ち負けがそろいました。次の節で、スコアを足します。