コンテンツにスキップ

ブタを倒してスコアを足す

ブタを倒してスコアを足す

前の 03 全ブタを倒したらクリア で、勝ち負けができました。この節では、 ブタを倒すたびにスコアを足して、画面に表示します。

今回さわる game/: scenes/game-scene.js を書き換え

前の節を終えていない人は、ここから始められます。

この節を始めるときのファイル

スコアと、その表示(右上の文字)を用意します。 倒すたびに加点するコード(下の「倒すたびに加点する」)も、下の差分に入っています。

scenes/game-scene.js
48
48
this.pigsLeft = pigPositions.length;
49
49
this.cleared = false;
50
50
51
this.score = 0;
52
this.scoreText = this.add
53
.text(700, 30, 'スコア: 0', { fontSize: '20px', color: '#333333' })
54
.setOrigin(1, 0.5);
55
51
56
// 衝突中に消すと不安定なので、ためて update でまとめて消す。
52
57
this.pendingRemoval = new Set();
scenes/game-scene.js
149
154
for (const pig of this.pendingRemoval) {
150
155
pig.destroy();
151
156
this.pigsLeft -= 1;
157
this.score += 1000;
158
this.scoreText.setText('スコア: ' + this.score);
152
159
}
153
160
this.pendingRemoval.clear();
  • this.score = 0 … スコアの数。最初は 0 です。
  • this.scoreText … スコアを表示する文字。setOrigin(1, 0.5) で右端そろえにして、右上に置きます。

ブタを消すたびに、スコアを足して表示を更新します。

  • this.score += 1000 … ブタ1匹につき 1000 点を足します。
  • this.scoreText.setText('スコア: ' + this.score) … 表示の文字を新しいスコアに書き換えます。

ブタを倒すたびに、右上のスコアが 1000 ずつ増えます。まだ結果画面にはスコアが出ません。 次の節で、クリア・ゲームオーバー画面にスコアを表示します。

↗ 新しいタブで開く
このステップの完成イメージ(実際に触って動かせます)

この節を終えたときのディレクトリ

Section titled “この節を終えたときのディレクトリ”
game
class ClearScene extends Phaser.Scene {
constructor() {
super('Clear');
}
create() {
this.add
.text(360, 200, 'クリア!', {
fontSize: '40px',
color: '#2e7d32',
fontStyle: 'bold',
})
.setOrigin(0.5);
this.add
.text(360, 280, 'クリックでスタートに戻る', {
fontSize: '18px',
color: '#555555',
})
.setOrigin(0.5);
this.input.once('pointerdown', () => this.scene.start('Start'));
}
}
class GameScene extends Phaser.Scene {
constructor() {
super('Game');
}
create() {
const groundX = 360;
const groundY = 440;
const groundWidth = 720;
const groundHeight = 80;
const groundTop = groundY - groundHeight / 2; // 地面の上面。物はこの高さに乗る
const ground = this.add.rectangle(
groundX,
groundY,
groundWidth,
groundHeight,
0x888888,
);
this.matter.add.gameObject(ground, { isStatic: true });
const boxSize = 40;
const towerX = 560;
for (let i = 0; i < 3; i++) {
const boxY = groundTop - boxSize / 2 - i * boxSize;
const box = this.add.rectangle(towerX, boxY, boxSize, boxSize, 0xdddddd);
box.setStrokeStyle(3, 0x333333);
this.matter.add.gameObject(box, { restitution: 0.1 });
}
const pigRadius = 16;
const pigPositions = [
{ x: 460, y: groundTop - pigRadius }, // 手前のブタ
{ x: towerX, y: groundTop - boxSize * 3 - pigRadius }, // タワーの上のブタ
{ x: 660, y: groundTop - pigRadius }, // 奥のブタ
];
for (const pos of pigPositions) {
const pig = this.add.circle(pos.x, pos.y, pigRadius, 0xaaaaaa);
pig.setStrokeStyle(3, 0x333333);
this.matter.add.gameObject(pig, {
shape: { type: 'circle', radius: pigRadius },
restitution: 0.2,
});
pig.isPig = true; // 衝突したときに見分けるための目印。
}
this.pigsLeft = pigPositions.length;
this.cleared = false;
this.score = 0;
this.scoreText = this.add
.text(700, 30, 'スコア: 0', { fontSize: '20px', color: '#333333' })
.setOrigin(1, 0.5);
// 衝突中に消すと不安定なので、ためて update でまとめて消す。
this.pendingRemoval = new Set();
this.matter.world.on('collisionstart', (event) => {
for (const pair of event.pairs) {
const gameObjectA = pair.bodyA.gameObject;
const gameObjectB = pair.bodyB.gameObject;
if (!gameObjectA || !gameObjectB) continue;
if (gameObjectA.isBird && gameObjectB.isPig)
this.pendingRemoval.add(gameObjectB);
if (gameObjectB.isBird && gameObjectA.isPig)
this.pendingRemoval.add(gameObjectA);
}
});
const anchor = { x: 140, y: 300 };
const power = 0.22; // 引っ張った長さを速さに変える倍率
const birdRadius = 18;
this.add.circle(anchor.x, anchor.y, 6, 0xbbbbbb);
const aim = this.add.graphics();
let birdsLeft = 5;
const reserve = this.add.graphics();
const drawReserve = () => {
reserve.clear();
for (let i = 0; i < birdsLeft; i++) {
const x = 30 + i * 26;
reserve.fillStyle(0xffffff, 1);
reserve.fillCircle(x, 40, 9);
reserve.lineStyle(2, 0x333333, 1);
reserve.strokeCircle(x, 40, 9);
}
};
// いま操作できる鳥。発射中やリロード待ちのときは null。
let bird = null;
let dragging = false;
const spawnBird = () => {
if (birdsLeft <= 0) return;
bird = this.add.circle(anchor.x, anchor.y, birdRadius, 0xffffff);
bird.setStrokeStyle(3, 0x333333);
this.matter.add.gameObject(bird, {
shape: { type: 'circle', radius: birdRadius },
restitution: 0.2,
});
// 待機中は動かないように静的にしておく。
bird.setStatic(true);
bird.isBird = true; // 同じく、鳥かどうかの目印。
};
drawReserve();
spawnBird();
this.input.on('pointerdown', () => {
if (!bird || dragging) return;
dragging = true;
});
this.input.on('pointermove', (pointer) => {
if (!dragging || !bird) return;
bird.setPosition(pointer.x, pointer.y);
const forwardX = anchor.x + (anchor.x - bird.x) * 1.5;
const forwardY = anchor.y + (anchor.y - bird.y) * 1.5;
aim.clear();
aim.lineStyle(2, 0x333333, 0.5);
aim.lineBetween(bird.x, bird.y, forwardX, forwardY);
});
this.input.on('pointerup', () => {
if (!dragging || !bird) return;
dragging = false;
aim.clear();
const vx = (anchor.x - bird.x) * power;
const vy = (anchor.y - bird.y) * power;
bird.setStatic(false);
bird.setVelocity(vx, vy);
bird = null;
birdsLeft -= 1;
drawReserve();
this.time.delayedCall(1200, () => {
if (birdsLeft > 0) {
spawnBird();
} else {
this.scene.start('GameOver');
}
});
});
}
update() {
for (const pig of this.pendingRemoval) {
pig.destroy();
this.pigsLeft -= 1;
this.score += 1000;
this.scoreText.setText('スコア: ' + this.score);
}
this.pendingRemoval.clear();
// 何度も遷移しないよう、クリアは1回だけ。
if (!this.cleared && this.pigsLeft <= 0) {
this.cleared = true;
this.scene.start('Clear');
}
}
}
class GameOverScene extends Phaser.Scene {
constructor() {
super('GameOver');
}
create() {
this.add
.text(360, 200, 'ゲームオーバー', {
fontSize: '36px',
color: '#c0392b',
fontStyle: 'bold',
})
.setOrigin(0.5);
this.add
.text(360, 280, 'クリックでスタートに戻る', {
fontSize: '18px',
color: '#555555',
})
.setOrigin(0.5);
this.input.once('pointerdown', () => this.scene.start('Start'));
}
}
class StartScene extends Phaser.Scene {
constructor() {
super('Start');
}
create() {
this.add
.text(360, 180, 'パチンコ物理ゲーム', {
fontSize: '36px',
color: '#5d4037',
fontStyle: 'bold',
})
.setOrigin(0.5);
const startText = this.add
.text(360, 300, '▶ スタート', {
fontSize: '28px',
color: '#ffffff',
backgroundColor: '#e08e3c',
padding: { x: 24, y: 12 },
})
.setOrigin(0.5)
.setInteractive({ useHandCursor: true });
startText.on('pointerdown', () => this.scene.start('Game'));
}
}
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>15 ブタを倒してスコアを足す</title>
<style>
body {
margin: 0;
overflow: hidden;
display: grid;
place-items: center;
min-height: 100vh;
background: #222;
}
canvas {
display: block;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script>
<script src="scenes/start-scene.js" defer></script>
<script src="scenes/game-scene.js" defer></script>
<script src="scenes/gameover-scene.js" defer></script>
<script src="scenes/clear-scene.js" defer></script>
<script src="main.js" defer></script>
</head>
<body></body>
</html>
new Phaser.Game({
type: Phaser.AUTO,
width: 720,
height: 480,
backgroundColor: '#fdf6e3',
physics: {
default: 'matter',
matter: { gravity: { y: 1 } },
},
scene: [StartScene, GameScene, GameOverScene, ClearScene],
});
この節を終えたときのファイル