落とすたびに数を表示する
画面に数値(HUD)を出す練習として、まず落とした回数を表示します。次の 2 つの節で、これを 「スコア」に育てていきます。
今回さわる
game/:scenes/game-scene.jsを書き換え
前の節を終えていない人は、ここから始められます。
数を持って、画面に文字を置く
Section titled “数を持って、画面に文字を置く”create() の状態に数を用意し、画面左上に文字を置きます。
scenes/game-scene.js を変更する
Section titled “scenes/game-scene.js を変更する”3030this.pendingRemoval = new Set();3131this.pendingMerge = [];3232this.isOver = false;33this.count = 0;3334
3435const g = this.add.graphics();3536g.fillStyle(0xe74c3c, 1);5455const floorW = box.right - box.left + box.wall * 2;5556this.matter.add.rectangle((box.left + box.right) / 2, box.bottom + box.wall / 2, floorW, box.wall, { isStatic: true });5657
58this.countText = this.add.text(16, 16, '0', {59 fontSize: '28px',60 color: '#333333',61 fontStyle: 'bold',62});63
5764this.input.on('pointerdown', (pointer) => {5865 if (this.isOver) return;6471 const ball = this.spawnBall(x, dropY, 0);6572 this.balls.push(ball);73
74 this.count += 1;75 this.countText.setText(String(this.count));6676});6777
6878this.matter.world.on('collisionstart', (event) => {this.add.text(x, y, 初期文字, スタイル) で文字を置けます。左上(16, 16)に「0」を出しておき、
あとで中身だけ書き換えます。書き換えたいので、this.countText としてシーンに覚えておきます。
落とすたびに増やして表示を更新する
Section titled “落とすたびに増やして表示を更新する”落とす処理の最後で数を増やし、文字を更新します。
setText(...) は、すでに置いてある文字の中身だけを差し替えます(毎回新しい文字を作らない)。
String(this.count) で数値を文字にしています。
ボールを落とすたびに、左上の数字が 1 ずつ増えます。数値を画面に出して更新する、という HUD の基本ができました。次の節で、これを「スコア」と呼び、結果画面にも引き継ぎます。