スコアを結果画面に表示する
前の節の「数」を スコア と呼ぶことにして、ゲームオーバー画面に引き継いで表示します。 ここでは シーンからシーンへ値を渡す やり方を覚えます。
今回さわる
game/:scenes/game-scene.jsとscenes/gameover-scene.jsを書き換え
前の節を終えていない人は、ここから始められます。
名前をスコアに変える
Section titled “名前をスコアに変える”count を score に、countText を scoreText に変え、表示も「スコア: N」にします。
scenes/game-scene.js を変更する
Section titled “scenes/game-scene.js を変更する”3030this.pendingRemoval = new Set();3131this.pendingMerge = [];3232this.isOver = false;33this.count = 0;33this.score = 0;3434
3535const g = this.add.graphics();3636g.fillStyle(0xe74c3c, 1);5555const floorW = box.right - box.left + box.wall * 2;5656this.matter.add.rectangle((box.left + box.right) / 2, box.bottom + box.wall / 2, floorW, box.wall, { isStatic: true });5757
58this.countText = this.add.text(16, 16, '0', {59 fontSize: '28px',58this.scoreText = this.add.text(16, 16, 'スコア: 0', {59 fontSize: '24px',6060 color: '#333333',6161 fontStyle: 'bold',6262});7272 const ball = this.spawnBall(x, dropY, 0);7373 this.balls.push(ball);7474
75 this.count += 1;76 this.countText.setText(String(this.count));75 this.score += 1;76 this.scoreText.setText('スコア: ' + this.score);7777});7878
7979this.matter.world.on('collisionstart', (event) => {144144 ball.overLineTime = (ball.overLineTime ?? 0) + delta;145145 if (ball.overLineTime > 1000) {146146 this.isOver = true;147 this.scene.start('GameOver');147 this.scene.start('GameOver', { score: this.score });148148 return;149149 }150150}落とす処理の更新もそれに合わせます。
ゲームオーバーへスコアを渡す
Section titled “ゲームオーバーへスコアを渡す”scene.start は、第 2 引数に渡したいデータを付けられます。ゲームオーバーへ移るところで
スコアを渡します。
受け取って表示する
Section titled “受け取って表示する”scenes/gameover-scene.js に init(data) を足します。init は create より前に呼ばれ、
scene.start で渡したデータを受け取れます。
scenes/gameover-scene.js を変更する
Section titled “scenes/gameover-scene.js を変更する”55 super('GameOver');66}77
8init(data) {9 this.finalScore = data.score ?? 0;10}11
812create() {913 this.add10 .text(200, 240, 'ゲームオーバー', {14 .text(200, 220, 'ゲームオーバー', {1115 fontSize: '32px',1216 color: '#c0392b',1317 fontStyle: 'bold',1519 .setOrigin(0.5);1620
1721this.add18 .text(200, 320, 'クリックでスタートに戻る', {22 .text(200, 300, 'スコア: ' + this.finalScore, {23 fontSize: '28px',24 color: '#333333',25 fontStyle: 'bold',26 })27 .setOrigin(0.5);28
29this.add30 .text(200, 360, 'クリックでスタートに戻る', {1931 fontSize: '18px',2032 color: '#555555',2133 })create() で、受け取ったスコアを表示します(レイアウトも少し整えます)。
?? 0 は「データが渡ってこなかったときは 0 にする」保険です。
ゲームオーバーになると、そのときのスコアが結果画面に出ます。ただし今のスコアは「落とした数」 のまま。次の節で、スコアの増え方を「合体で大きくなったとき」に変えて、ゲームらしくします。