ブタを倒してスコアを足す
前の 03 全ブタを倒したらクリア で、勝ち負けができました。この節では、 ブタを倒すたびにスコアを足して、画面に表示します。
今回さわる
game/:scenes/game-scene.jsを書き換え
前の節を終えていない人は、ここから始められます。
スコアの表示を用意する
Section titled “スコアの表示を用意する”スコアと、その表示(右上の文字)を用意します。 倒すたびに加点するコード(下の「倒すたびに加点する」)も、下の差分に入っています。
scenes/game-scene.js を変更する
Section titled “scenes/game-scene.js を変更する”4848this.pigsLeft = pigPositions.length;4949this.cleared = false;5050
51this.score = 0;52this.scoreText = this.add53 .text(700, 30, 'スコア: 0', { fontSize: '20px', color: '#333333' })54 .setOrigin(1, 0.5);55
5156// 衝突中に消すと不安定なので、ためて update でまとめて消す。5257this.pendingRemoval = new Set();149154for (const pig of this.pendingRemoval) {150155 pig.destroy();151156 this.pigsLeft -= 1;157 this.score += 1000;158 this.scoreText.setText('スコア: ' + this.score);152159}153160this.pendingRemoval.clear();this.score = 0… スコアの数。最初は 0 です。this.scoreText… スコアを表示する文字。setOrigin(1, 0.5)で右端そろえにして、右上に置きます。
倒すたびに加点する
Section titled “倒すたびに加点する”ブタを消すたびに、スコアを足して表示を更新します。
this.score += 1000… ブタ1匹につき 1000 点を足します。this.scoreText.setText('スコア: ' + this.score)… 表示の文字を新しいスコアに書き換えます。
ブタを倒すたびに、右上のスコアが 1000 ずつ増えます。まだ結果画面にはスコアが出ません。 次の節で、クリア・ゲームオーバー画面にスコアを表示します。