コンテンツにスキップ

ぶつかると1つになる

ぶつかると1つになる

ここからが「スイカゲームらしさ」の本番です。まずは一番の核、ボール同士がぶつかったら 1 つにまとめる(合体) を作ります。この節では大きさはまだ変えません。仕組みだけ入れます。

土台は 02 章の最後(シーン分割版) です。 以降は scenes/game-scene.js を中心に手を入れます。

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

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

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

create() の状態に、「消す予定のボール」を覚えておく入れ物を足します。

scenes/game-scene.js
17
17
this.radius = 25;
18
18
this.lineY = 190;
19
19
this.balls = [];
20
this.pendingRemoval = new Set();
20
21
this.isOver = false;
21
22
22
23
const g = this.add.graphics();
scenes/game-scene.js
51
52
const x = Phaser.Math.Clamp(pointer.x, box.left + this.radius, box.right - this.radius);
52
53
53
54
const ball = this.add.circle(x, dropY, this.radius, 0x333333);
54
55
55
this.matter.add.gameObject(ball, {
56
56
shape: {
57
57
type: 'circle',
scenes/game-scene.js
62
62
this.balls.push(ball);
63
63
});
64
65
this.matter.world.on('collisionstart', (event) => {
66
for (const pair of event.pairs) {
67
// gameObject を持つのがボール(壁は持たない)
68
const ballA = pair.bodyA.gameObject;
69
const ballB = pair.bodyB.gameObject;
70
if (!ballA || !ballB) continue;
71
if (this.pendingRemoval.has(ballA) || this.pendingRemoval.has(ballB)) continue;
72
this.pendingRemoval.add(ballB);
73
}
74
});
64
75
}
65
76
66
77
update(time, delta) {
78
if (this.pendingRemoval.size > 0) {
79
for (const ball of this.pendingRemoval) {
80
Phaser.Utils.Array.Remove(this.balls, ball);
81
ball.destroy();
82
}
83
this.pendingRemoval.clear();
84
}
85
67
86
if (this.isOver) return;
68
87
69
88
// 落下中は速いので、止まって線を超え続けたときだけゲームオーバー(誤検出を防ぐ)

Set は「重複しない集まり」です。1 回の衝突で同じボールを二重に登録しないために使います。

衝突が起きたら片方を消す予定にする

Section titled “衝突が起きたら片方を消す予定にする”

Matter は物体同士がぶつかった瞬間に collisionstart イベントを出します。create() の末尾で これを受け取ります。

  • event.pairs … ぶつかった物体の組み合わせの一覧。
  • pair.bodyA.gameObject … 物理ボディにくっついている見た目(=ボール)。壁は matter.add.rectangle で作っていて gameObject を持たないので、if (!ballA || !ballB) continue; で「壁との衝突」を除けます。
  • すでに消す予定のボールが絡む組はスキップし、そうでなければ ballB を消す予定に入れます。

なぜここで即 destroy() しないのか。 衝突イベントは物理計算の途中で呼ばれます。その最中に ボールを消すと不安定になりやすいので、いったん「消す予定」に貯めておき、あとでまとめて片付けます。

update() の先頭で、貯まった「消す予定」を処理します。

this.balls(判定に使う一覧)からも取り除いてから destroy() します。

ボールを重ねると、ぶつかった瞬間に片方が消えて 1 個になります。まだ大きさは変わりませんが、 「合体」の仕組みができました。次の節で、合体したら大きくします。

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

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

Section titled “この節を終えたときのディレクトリ”
game
// ゲーム本編
class GameScene extends Phaser.Scene {
constructor() {
super('Game');
}
create() {
const box = {
left: 60,
right: 340,
top: 150,
bottom: 540,
wall: 12
};
this.radius = 25;
this.lineY = 190;
this.balls = [];
this.pendingRemoval = new Set();
this.isOver = false;
const g = this.add.graphics();
g.fillStyle(0xe74c3c, 1);
g.fillRect(box.left - box.wall, box.top, box.wall, box.bottom - box.top);
g.fillStyle(0x2ecc71, 1);
g.fillRect(box.right, box.top, box.wall, box.bottom - box.top);
g.fillStyle(0x3498db, 1);
g.fillRect(box.left - box.wall, box.bottom, box.right - box.left + box.wall * 2, box.wall);
g.lineStyle(2, 0xc0392b, 0.8);
g.beginPath();
g.moveTo(box.left, this.lineY);
g.lineTo(box.right, this.lineY);
g.strokePath();
const wallH = box.bottom - box.top;
const wallCY = (box.top + box.bottom) / 2;
this.matter.add.rectangle(box.left - box.wall / 2, wallCY, box.wall, wallH, { isStatic: true });
this.matter.add.rectangle(box.right + box.wall / 2, wallCY, box.wall, wallH, { isStatic: true });
const floorW = box.right - box.left + box.wall * 2;
this.matter.add.rectangle((box.left + box.right) / 2, box.bottom + box.wall / 2, floorW, box.wall, { isStatic: true });
this.input.on('pointerdown', (pointer) => {
if (this.isOver) return;
const dropY = 100;
// 箱の内側からはみ出さないよう X を制限する
const x = Phaser.Math.Clamp(pointer.x, box.left + this.radius, box.right - this.radius);
const ball = this.add.circle(x, dropY, this.radius, 0x333333);
this.matter.add.gameObject(ball, {
shape: {
type: 'circle',
radius: this.radius
},
restitution: 0.2, // 跳ね返りの強さ(0=跳ねない 〜 1=よく跳ねる)
});
this.balls.push(ball);
});
this.matter.world.on('collisionstart', (event) => {
for (const pair of event.pairs) {
// gameObject を持つのがボール(壁は持たない)
const ballA = pair.bodyA.gameObject;
const ballB = pair.bodyB.gameObject;
if (!ballA || !ballB) continue;
if (this.pendingRemoval.has(ballA) || this.pendingRemoval.has(ballB)) continue;
this.pendingRemoval.add(ballB);
}
});
}
update(time, delta) {
if (this.pendingRemoval.size > 0) {
for (const ball of this.pendingRemoval) {
Phaser.Utils.Array.Remove(this.balls, ball);
ball.destroy();
}
this.pendingRemoval.clear();
}
if (this.isOver) return;
// 落下中は速いので、止まって線を超え続けたときだけゲームオーバー(誤検出を防ぐ)
for (const ball of this.balls) {
if (!ball.body) continue;
const isSlow = ball.body.speed < 1;
const top = ball.y - this.radius;
if (!isSlow || top >= this.lineY) {
ball.overLineTime = 0;
continue;
}
ball.overLineTime = (ball.overLineTime ?? 0) + delta;
if (ball.overLineTime > 1000) {
this.isOver = true;
this.scene.start('GameOver');
return;
}
}
}
}
// ゲームオーバー画面
class GameOverScene extends Phaser.Scene {
constructor() {
super('GameOver');
}
create() {
this.add
.text(200, 240, 'ゲームオーバー', {
fontSize: '32px',
color: '#c0392b',
fontStyle: 'bold',
})
.setOrigin(0.5);
this.add
.text(200, 320, 'クリックでスタートに戻る', {
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(200, 220, 'スイカゲーム風', {
fontSize: '32px',
color: '#8b5a2b',
fontStyle: 'bold',
})
.setOrigin(0.5);
const startText = this.add
.text(200, 340, '▶ スタート', {
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>11 ボール同士がぶつかると1つになる(大きさは変えない)</title>
<style>
body {
margin: 0;
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>
// ボール同士がぶつかると1つになる(大きさは変えない)。
new Phaser.Game({
type: Phaser.AUTO,
width: 400,
height: 600,
backgroundColor: '#fdf6e3',
physics: {
default: 'matter',
matter: { gravity: { y: 1 } },
},
scene: [StartScene, GameScene, GameOverScene],
});
この節を終えたときのファイル