コンテンツにスキップ

全ブタを倒したらクリア

全ブタを倒したらクリア

前の 02 当たったブタを消す で、ブタを消せるようになりました。 この節では、ブタを全部倒したら「クリア画面」へ進むようにします。勝ちの条件です。

今回さわる game/: scenes/game-scene.js を書き換え、scenes/clear-scene.js を追加、index.html と main.js に登録

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

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

残りの数を覚えておきます。0 になったらクリアです。 update の書き換え(下の「倒すたびに減らし、0 でクリアへ」)も、下の差分に入っています。

scenes/game-scene.js
45
45
pig.isPig = true; // 衝突したときに見分けるための目印。
46
46
}
47
47
48
this.pigsLeft = pigPositions.length;
49
this.cleared = false;
50
48
51
// 衝突中に消すと不安定なので、ためて update でまとめて消す。
49
52
this.pendingRemoval = new Set();
scenes/game-scene.js
145
148
update() {
146
149
for (const pig of this.pendingRemoval) {
147
150
pig.destroy();
151
this.pigsLeft -= 1;
148
152
}
149
153
this.pendingRemoval.clear();
154
155
// 何度も遷移しないよう、クリアは1回だけ。
156
if (!this.cleared && this.pigsLeft <= 0) {
157
this.cleared = true;
158
this.scene.start('Clear');
159
}
150
160
}
151
161
}
  • this.pigsLeft … 残りのブタの数。最初は置いた数(pigPositions.length)です。
  • this.cleared … もうクリアしたかどうかの印。クリア画面へ二重に進まないために使います。

倒すたびに減らし、0 でクリアへ

Section titled “倒すたびに減らし、0 でクリアへ”

ブタを消すたびに残りを1つ減らします。0 になったらクリア画面へ進みます。

  • this.pigsLeft -= 1 … ブタを1匹消すたびに残りを減らします。
  • if (!this.cleared && this.pigsLeft <= 0) … まだクリアしておらず、残りが 0 になったら実行します。
  • this.cleared = true … 印を立てて、次のフレームでもう一度クリアに進まないようにします。
  • this.scene.start('Clear') … クリア画面へ切り替えます。
scenes/clear-scene.js
1
class ClearScene extends Phaser.Scene {
2
constructor() {
3
super('Clear');
4
}
5
6
create() {
7
this.add
8
.text(360, 200, 'クリア!', {
9
fontSize: '40px',
10
color: '#2e7d32',
11
fontStyle: 'bold',
12
})
13
.setOrigin(0.5);
14
15
this.add
16
.text(360, 280, 'クリックでスタートに戻る', {
17
fontSize: '18px',
18
color: '#555555',
19
})
20
.setOrigin(0.5);
21
22
this.input.once('pointerdown', () => this.scene.start('Start'));
23
}
24
}

登録も忘れずに。作ったファイルは 2 か所に足します。

まず index.html の読み込みです。main.js より前に置きます。main.js が起動する時点で ClearScene が用意されていないと、ClearScene is not defined で止まります。

index.html
3
3
<head>
4
4
<meta charset="utf-8" />
5
5
<meta name="viewport" content="width=device-width, initial-scale=1" />
6
<title>13 当たったブタを消す</title>
6
<title>14 全ブタを倒したらクリア</title>
7
7
<style>
8
8
body {
9
9
margin: 0;
index.html
21
21
<script src="scenes/start-scene.js" defer></script>
22
22
<script src="scenes/game-scene.js" defer></script>
23
23
<script src="scenes/gameover-scene.js" defer></script>
24
<script src="scenes/clear-scene.js" defer></script>
24
25
<script src="main.js" defer></script>
25
26
</head>
26
27
<body></body>

つぎに main.js の scene 配列に ClearScene を加えます。

main.js
7
7
default: 'matter',
8
8
matter: { gravity: { y: 1 } },
9
9
},
10
scene: [StartScene, GameScene, GameOverScene],
10
scene: [StartScene, GameScene, GameOverScene, ClearScene],
11
11
});

ブタを3匹とも倒すと「クリア!」の画面になります。鳥を撃ち切って倒しきれなければ、 これまでどおりゲームオーバーです。これで勝ち負けがそろいました。次の節で、スコアを足します。

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

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

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;
// 衝突中に消すと不安定なので、ためて 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.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>14 全ブタを倒したらクリア</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],
});
この節を終えたときのファイル