コンテンツにスキップ

当たったブタを消す

当たったブタを消す

前の 01 標的(ブタ)を置く で、ブタを置きました。この節では、鳥が当たった ブタを消します。物理エンジンの「ぶつかった」お知らせを受け取って、消す仕組みを作ります。

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

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

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

衝突したとき「どれが鳥で、どれがブタか」を見分けられるよう、目印(印の変数)をつけます。 ブタを作るところに pig.isPig = true、鳥を作るところに bird.isBird = true を足します。 衝突を受け取るコードと、まとめて消す update も下の差分に入っています(それぞれ下の見出しで説明します)。

scenes/game-scene.js
42
42
shape: { type: 'circle', radius: pigRadius },
43
43
restitution: 0.2,
44
44
});
45
pig.isPig = true; // 衝突したときに見分けるための目印。
45
46
}
46
47
48
// 衝突中に消すと不安定なので、ためて update でまとめて消す。
49
this.pendingRemoval = new Set();
50
51
this.matter.world.on('collisionstart', (event) => {
52
for (const pair of event.pairs) {
53
const gameObjectA = pair.bodyA.gameObject;
54
const gameObjectB = pair.bodyB.gameObject;
55
if (!gameObjectA || !gameObjectB) continue;
56
if (gameObjectA.isBird && gameObjectB.isPig)
57
this.pendingRemoval.add(gameObjectB);
58
if (gameObjectB.isBird && gameObjectA.isPig)
59
this.pendingRemoval.add(gameObjectA);
60
}
61
});
62
47
63
const anchor = { x: 140, y: 300 };
48
64
const power = 0.22; // 引っ張った長さを速さに変える倍率
49
65
const birdRadius = 18;
scenes/game-scene.js
79
95
});
80
96
// 待機中は動かないように静的にしておく。
81
97
bird.setStatic(true);
98
bird.isBird = true; // 同じく、鳥かどうかの目印。
82
99
};
83
100
84
101
drawReserve();
scenes/game-scene.js
124
141
});
125
142
});
126
143
}
144
145
update() {
146
for (const pig of this.pendingRemoval) {
147
pig.destroy();
148
}
149
this.pendingRemoval.clear();
150
}
127
151
}

衝突を受け取って消す予約をする

Section titled “衝突を受け取って消す予約をする”

物理エンジンは、何かがぶつかると collisionstart というお知らせを出します。これを受け取って、 「鳥」と「ブタ」がぶつかっていたら、そのブタを消す予約に入れます。

  • this.pendingRemoval = new Set() … 「これから消すブタ」をためておく入れ物です。
  • this.matter.world.on('collisionstart', ...) … 何かがぶつかった瞬間に呼ばれます。
  • event.pairs … ぶつかった相手の組み合わせのリスト。1つずつ調べます。
  • pair.bodyA.gameObject … ぶつかった物の見た目(鳥・ブタ・箱)。壁や地面は持っていないので null になります。
  • if (a.isBird && b.isPig) … 片方が鳥・もう片方がブタなら、そのブタを消す予約に入れます。逆の組み合わせも見ます。

ぶつかった瞬間にその場で消すと不安定になりがちなので、毎フレーム呼ばれる update で まとめて消します。

  • update() … 毎フレーム自動で呼ばれるメソッドです。
  • pig.destroy() … ブタを画面と物理世界から消します。
  • this.pendingRemoval.clear() … 消し終わったら、予約の入れ物を空にします。

鳥をブタに当てると、ブタが消えます。箱を崩して道を作り、奥のブタに当てる楽しさが出てきました。 次の節で、ブタを全部倒したら「クリア」になるようにします。

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

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

Section titled “この節を終えたときのディレクトリ”
game
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; // 衝突したときに見分けるための目印。
}
// 衝突中に消すと不安定なので、ためて 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.pendingRemoval.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>13 当たったブタを消す</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="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],
});
この節を終えたときのファイル