大きさで色を変える
大きさを「半径の数値」で持つと、色分けや「同じ大きさ同士だけ合体」といった判定がやりにくく なります。この節では、大きさを 段階(grade) という整数で表すように切り替え、段階ごとに 色を変えます。
grade = 0, 1, 2, …と段階が上がるほど大きく、色が変わる- 半径は
20 + grade * 10で計算する - 色は段階に対応した表
COLORSから選ぶ
今回さわる
game/:scenes/game-scene.jsを書き換え
前の節を終えていない人は、ここから始められます。
色の表を用意する
Section titled “色の表を用意する”scenes/game-scene.js の先頭(クラスの外)に、段階ごとの色を並べた表を置きます。この表は
spawnBall から参照します。
scenes/game-scene.js を変更する
Section titled “scenes/game-scene.js を変更する”11// ゲーム本編22
3const COLORS = [4 0xd7263d,5 0xff7096,6 0x8e44ad,7 0xe67e22,8 0x2e86de,9 0x27ae60,10 0xf1c40f,11];12
313class GameScene extends Phaser.Scene {414 constructor() {515 super('Game');1323 bottom: 540,1424 wall: 121525};16const ballRadius = 20;17const grow = 10;26const baseRadius = 20;1827
1928this.lineY = 190;2029this.balls = [];5160 const dropY = 100;5261
5362 // 箱の内側からはみ出さないよう X を制限する54 const x = Phaser.Math.Clamp(pointer.x, box.left + ballRadius, box.right - ballRadius);63 const x = Phaser.Math.Clamp(pointer.x, box.left + baseRadius, box.right - baseRadius);5564
56 const ball = this.spawnBall(x, dropY, ballRadius);65 const ball = this.spawnBall(x, dropY, 0);5766 this.balls.push(ball);5867});6978 this.pendingMerge.push({7079 x: (ballA.x + ballB.x) / 2,7180 y: (ballA.y + ballB.y) / 2,72 radius: ballA.radius + grow,81 grade: ballA.grade + 1,7382 });7483 }7584 });7685}7786
78spawnBall(x, y, radius) {79 const ball = this.add.circle(x, y, radius, 0x333333);87spawnBall(x, y, grade) {88 const radius = 20 + grade * 10;89 const color = COLORS[Phaser.Math.Clamp(grade, 0, COLORS.length - 1)];90
91 const ball = this.add.circle(x, y, radius, color);92 ball.grade = grade;8093 ball.radius = radius; // 線の判定などで使うので半径を持たせておく8194 this.matter.add.gameObject(ball, {8295 shape: {99112if (this.pendingMerge.length > 0) {100113 for (const m of this.pendingMerge) {101 const ball = this.spawnBall(m.x, m.y, m.radius);114 const ball = this.spawnBall(m.x, m.y, m.grade);102115 this.balls.push(ball);103116 }104117 this.pendingMerge.length = 0;spawnBall を「半径」から「段階」に変える
Section titled “spawnBall を「半径」から「段階」に変える”spawnBall の引数を radius から grade に変え、半径と色をその場で計算します。ボールには
grade を持たせます。
Clamp(grade, 0, COLORS.length - 1) は、段階が表の数を超えても最後の色で止めるための保険です。
呼び出し側も段階で渡す
Section titled “呼び出し側も段階で渡す”落とすときは一番下の段階 0 を渡します(ballRadius は使わなくなり、基準半径は baseRadius
としてクランプ用にだけ残します)。
合体予定も、半径ではなく段階を 1 つ上げた値で積みます。
update() の合体処理も this.spawnBall(m.x, m.y, m.grade) に変えます。
落としたボールは一番小さい色、合体するたびに段階が上がって大きく・別の色になります。 「段階」で持てるようになったので、次の節で「同じ段階同士だけ合体」を実装できます。