コンテンツにスキップ

設定で音を切り替える

設定で音を切り替える

スタート画面に「効果音」「BGM」の ON/OFF ボタンを付け、その設定に従って音を鳴らす/鳴らさない を切り替えます。設定はブラウザの localStorage に保存して、次に開いたときも覚えているようにします。

  • 保存キー: 効果音 = suika-sfx、BGM = suika-bgm
  • 値は 'on' / 'off'。未設定なら ON 扱い(!== 'off' で判定)

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

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

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

スタート画面にトグルを付ける

Section titled “スタート画面にトグルを付ける”

scenes/start-scene.js のタイトルとスタートボタンの位置を少し上げ、下に 2 つのトグルを置きます。

scenes/start-scene.js
7
7
create() {
8
8
this.add
9
.text(200, 220, 'スイカゲーム風', {
9
.text(200, 180, 'スイカゲーム風', {
10
10
fontSize: '32px',
11
11
color: '#8b5a2b',
12
12
fontStyle: 'bold',
scenes/start-scene.js
15
15
.setOrigin(0.5);
16
16
17
17
const startText = this.add
18
.text(200, 340, '▶ スタート', {
18
.text(200, 290, '▶ スタート', {
19
19
fontSize: '28px',
20
20
color: '#ffffff',
21
21
backgroundColor: '#e08e3c',
scenes/start-scene.js
23
23
})
24
24
.setOrigin(0.5)
25
25
.setInteractive({ useHandCursor: true });
26
27
26
startText.on('pointerdown', () => this.scene.start('Game'));
27
28
this.makeToggle(200, 400, '効果音', 'suika-sfx');
29
this.makeToggle(200, 450, 'BGM', 'suika-bgm');
28
30
}
31
32
makeToggle(x, y, label, key) {
33
const text = this.add
34
.text(x, y, '', {
35
fontSize: '22px',
36
color: '#333333',
37
backgroundColor: '#f0e6d2',
38
padding: { x: 16, y: 8 },
39
})
40
.setOrigin(0.5)
41
.setInteractive({ useHandCursor: true });
42
43
const render = () => {
44
const on = localStorage.getItem(key) !== 'off';
45
text.setText(label + ': ' + (on ? 'ON' : 'OFF'));
46
text.setColor(on ? '#27ae60' : '#999999');
47
};
48
render();
49
50
text.on('pointerdown', () => {
51
const on = localStorage.getItem(key) !== 'off';
52
localStorage.setItem(key, on ? 'off' : 'on');
53
render();
54
});
55
}
29
56
}

トグル 1 個分の作りは同じなので、makeToggle(x, y, ラベル, キー) というメソッドにまとめます。

  • localStorage.getItem(key) … 保存された値を読みます。未保存なら null なので !== 'off' は真 = ON 扱い。
  • render() … 今の状態に合わせて文字(ON/OFF)と色を描き直す小さな関数。
  • クリックすると値を反転させて保存し、render() で見た目を更新します。

scenes/game-scene.js の create() の先頭付近で、設定を読み取っておきます。

scenes/game-scene.js
32
32
this.isOver = false;
33
33
this.score = 0;
34
34
35
// 未設定なら ON 扱い
36
this.sfxOn = localStorage.getItem('suika-sfx') !== 'off';
37
this.bgmOn = localStorage.getItem('suika-bgm') !== 'off';
38
35
39
const g = this.add.graphics();
36
40
g.fillStyle(0xe74c3c, 1);
37
41
g.fillRect(box.left - box.wall, box.top, box.wall, box.bottom - box.top);
scenes/game-scene.js
57
61
// シーンを抜けるとき止める
58
62
this.bgm = this.sound.add('bgm', { loop: true, volume: 0.4 });
59
this.bgm.play();
63
if (this.bgmOn) this.bgm.play();
60
64
this.events.once('shutdown', () => this.bgm.stop());
61
65
62
66
this.scoreText = this.add.text(16, 16, 'スコア: 0', {
scenes/game-scene.js
76
80
const ball = this.spawnBall(x, dropY, 0);
77
81
this.balls.push(ball);
78
this.sound.play('drop');
82
if (this.sfxOn) this.sound.play('drop');
79
83
});
80
84
81
85
this.matter.world.on('collisionstart', (event) => {
scenes/game-scene.js
99
103
this.score += newGrade * 10;
100
104
this.scoreText.setText('スコア: ' + this.score);
101
this.sound.play('merge');
105
if (this.sfxOn) this.sound.play('merge');
102
106
}
103
107
});
104
108
}

あとは、音を鳴らしている 3 か所を、フラグで囲むだけです。

loadFlag のような共通関数は作らず、localStorage.getItem(key) !== 'off' をそのまま各所に 書いています。短い判定なので、まとめるより読んだままのほうが分かりやすいためです。

スタート画面で効果音・BGM を OFF にしてから始めると、その音が鳴りません。ページを開き直しても 設定が残っていることも確認してください。

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

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

Section titled “この節を終えたときのディレクトリ”
game
(画像などの、文字ではないファイルです。ZIP には入っています)
(画像などの、文字ではないファイルです。ZIP には入っています)
(画像などの、文字ではないファイルです。ZIP には入っています)
(画像などの、文字ではないファイルです。ZIP には入っています)
(画像などの、文字ではないファイルです。ZIP には入っています)
(画像などの、文字ではないファイルです。ZIP には入っています)
(画像などの、文字ではないファイルです。ZIP には入っています)
(画像などの、文字ではないファイルです。ZIP には入っています)
このディレクトリの素材のクレジットとライセンス
■ フルーツ画像 (1f3xx.png)
Twemoji (https://github.com/twitter/twemoji)
グラフィックは CC-BY 4.0 (https://creativecommons.org/licenses/by/4.0/)
© Twitter, Inc and other contributors
■ 効果音 (merge.wav, drop.wav)
Kenney Interface Sounds (https://kenney.nl)
CC0 1.0 (パブリックドメイン相当)。詳細は LICENSE.txt を参照。
■ BGM (bgm.wav)
このハンズオン用に自作したループ曲。CC0 1.0 として提供(自由に利用・改変・再配布可)。
(画像などの、文字ではないファイルです。ZIP には入っています)
Interface Sounds (1.0)
Created/distributed by Kenney (www.kenney.nl)
Creation date: 11-02-2020
------------------------------
License: (Creative Commons Zero, CC0)
http://creativecommons.org/publicdomain/zero/1.0/
This content is free to use in personal, educational and commercial projects.
Support us by crediting Kenney or www.kenney.nl (this is not mandatory)
------------------------------
Donate: http://support.kenney.nl
Patreon: http://patreon.com/kenney/
Follow on Twitter for updates:
http://twitter.com/KenneyNL
(画像などの、文字ではないファイルです。ZIP には入っています)
// ゲーム本編
// twemoji のコードポイント名(段階が上がるほど後ろのフルーツ)
const FRUITS = ['1f352', '1f353', '1f347', '1f34a', '1f34e', '1f350', '1f349'];
class GameScene extends Phaser.Scene {
constructor() {
super('Game');
}
preload() {
FRUITS.forEach((cp, i) => this.load.image('fruit' + i, 'assets/' + cp + '.png'));
this.load.audio('merge', 'assets/merge.wav');
this.load.audio('drop', 'assets/drop.wav');
this.load.audio('bgm', 'assets/bgm.wav');
}
create() {
const box = {
left: 60,
right: 340,
top: 150,
bottom: 540,
wall: 12
};
const baseRadius = 20;
this.lineY = 190;
this.balls = [];
this.pendingRemoval = new Set();
this.pendingMerge = [];
this.isOver = false;
this.score = 0;
// 未設定なら ON 扱い
this.sfxOn = localStorage.getItem('suika-sfx') !== 'off';
this.bgmOn = localStorage.getItem('suika-bgm') !== 'off';
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.bgm = this.sound.add('bgm', { loop: true, volume: 0.4 });
if (this.bgmOn) this.bgm.play();
this.events.once('shutdown', () => this.bgm.stop());
this.scoreText = this.add.text(16, 16, 'スコア: 0', {
fontSize: '24px',
color: '#333333',
fontStyle: 'bold',
});
this.input.on('pointerdown', (pointer) => {
if (this.isOver) return;
const dropY = 100;
// 箱の内側からはみ出さないよう X を制限する
const x = Phaser.Math.Clamp(pointer.x, box.left + baseRadius, box.right - baseRadius);
const ball = this.spawnBall(x, dropY, 0);
this.balls.push(ball);
if (this.sfxOn) this.sound.play('drop');
});
this.matter.world.on('collisionstart', (event) => {
for (const pair of event.pairs) {
const ballA = pair.bodyA.gameObject;
const ballB = pair.bodyB.gameObject;
if (!ballA || !ballB) continue;
if (this.pendingRemoval.has(ballA) || this.pendingRemoval.has(ballB)) continue;
// 同じ段階どうしだけ合体する(違う大きさはぶつかるだけ)
if (ballA.grade !== ballB.grade) continue;
this.pendingRemoval.add(ballA);
this.pendingRemoval.add(ballB);
const newGrade = ballA.grade + 1;
this.pendingMerge.push({
x: (ballA.x + ballB.x) / 2,
y: (ballA.y + ballB.y) / 2,
grade: newGrade,
});
this.score += newGrade * 10;
this.scoreText.setText('スコア: ' + this.score);
if (this.sfxOn) this.sound.play('merge');
}
});
}
spawnBall(x, y, grade) {
const radius = 20 + grade * 10;
const key = 'fruit' + Phaser.Math.Clamp(grade, 0, FRUITS.length - 1);
const ball = this.add.image(x, y, key);
ball.setDisplaySize(radius * 2, radius * 2);
ball.grade = grade;
ball.radius = radius; // 線の判定などで使うので半径を持たせておく
this.matter.add.gameObject(ball, {
shape: {
type: 'circle',
radius: radius
},
restitution: 0.2, // 跳ね返りの強さ(0=跳ねない 〜 1=よく跳ねる)
});
return ball;
}
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.pendingMerge.length > 0) {
for (const m of this.pendingMerge) {
const ball = this.spawnBall(m.x, m.y, m.grade);
this.balls.push(ball);
}
this.pendingMerge.length = 0;
}
if (this.isOver) return;
// 落下中は速いので、止まって線を超え続けたときだけゲームオーバー(誤検出を防ぐ)
for (const ball of this.balls) {
if (!ball.body) continue;
const isSlow = ball.body.speed < 1;
const top = ball.y - ball.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', { score: this.score });
return;
}
}
}
}
// ゲームオーバー画面
class GameOverScene extends Phaser.Scene {
constructor() {
super('GameOver');
}
init(data) {
this.finalScore = data.score ?? 0;
}
create() {
this.add
.text(200, 220, 'ゲームオーバー', {
fontSize: '32px',
color: '#c0392b',
fontStyle: 'bold',
})
.setOrigin(0.5);
this.add
.text(200, 300, 'スコア: ' + this.finalScore, {
fontSize: '28px',
color: '#333333',
fontStyle: 'bold',
})
.setOrigin(0.5);
this.add
.text(200, 360, 'クリックでスタートに戻る', {
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, 180, 'スイカゲーム風', {
fontSize: '32px',
color: '#8b5a2b',
fontStyle: 'bold',
})
.setOrigin(0.5);
const startText = this.add
.text(200, 290, '▶ スタート', {
fontSize: '28px',
color: '#ffffff',
backgroundColor: '#e08e3c',
padding: { x: 24, y: 12 },
})
.setOrigin(0.5)
.setInteractive({ useHandCursor: true });
startText.on('pointerdown', () => this.scene.start('Game'));
this.makeToggle(200, 400, '効果音', 'suika-sfx');
this.makeToggle(200, 450, 'BGM', 'suika-bgm');
}
makeToggle(x, y, label, key) {
const text = this.add
.text(x, y, '', {
fontSize: '22px',
color: '#333333',
backgroundColor: '#f0e6d2',
padding: { x: 16, y: 8 },
})
.setOrigin(0.5)
.setInteractive({ useHandCursor: true });
const render = () => {
const on = localStorage.getItem(key) !== 'off';
text.setText(label + ': ' + (on ? 'ON' : 'OFF'));
text.setColor(on ? '#27ae60' : '#999999');
};
render();
text.on('pointerdown', () => {
const on = localStorage.getItem(key) !== 'off';
localStorage.setItem(key, on ? 'off' : 'on');
render();
});
}
}
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>22 設定で音を切り替える</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>
// 設定で効果音・BGM の ON/OFF を切り替える(localStorage に保存)。
new Phaser.Game({
type: Phaser.AUTO,
width: 400,
height: 600,
backgroundColor: '#fdf6e3',
physics: {
default: 'matter',
matter: { gravity: { y: 1 } },
},
scene: [StartScene, GameScene, GameOverScene],
});
この節を終えたときのファイル