設定で音を切り替える
前の 03 BGM を流す で音がそろいました。最後に、スタート画面で効果音と BGM のオン・オフを切り替えられるようにします。設定はブラウザに保存して、次に開いたときも 覚えているようにします。これでゲームの完成です。
今回さわる
game/:scenes/start-scene.js・scenes/game-scene.jsを書き換え
前の節を終えていない人は、ここから始められます。
スタート画面にトグルを足す
Section titled “スタート画面にトグルを足す”音の設定を切り替えるボタン(トグル)を作る仕組みを足します。設定は
localStorage(ブラウザに残る保存場所)にしまいます。
下の差分は create の閉じかっこ } をまたいでいます。create の末尾に makeToggle を呼ぶ2行を足し、
} の後の makeToggle(x, y, label, key) { からはクラス直下のメソッドです。
scenes/start-scene.js を変更する
Section titled “scenes/start-scene.js を変更する”55create() {66 this.add7 .text(360, 180, 'パチンコ物理ゲーム', {7 .text(360, 140, 'パチンコ物理ゲーム', {88 fontSize: '36px',99 color: '#5d4037',1010 fontStyle: 'bold',1313 .setOrigin(0.5);1414
1515const startText = this.add16 .text(360, 300, '▶ スタート', {16 .text(360, 250, '▶ スタート', {1717 fontSize: '28px',1818 color: '#ffffff',1919 backgroundColor: '#e08e3c',2323 .setInteractive({ useHandCursor: true });2424
2525 startText.on('pointerdown', () => this.scene.start('Game'));26
27 this.makeToggle(360, 350, '効果音', 'slingshot-sfx');28 this.makeToggle(360, 410, 'BGM', 'slingshot-bgm');2629 }30
31 makeToggle(x, y, label, key) {32 const text = this.add33 .text(x, y, '', {34 fontSize: '22px',35 color: '#333333',36 backgroundColor: '#f0e6d2',37 padding: { x: 16, y: 8 },38 })39 .setOrigin(0.5)40 .setInteractive({ useHandCursor: true });41
42 const render = () => {43 const on = localStorage.getItem(key) !== 'off';44 text.setText(label + ': ' + (on ? 'ON' : 'OFF'));45 text.setColor(on ? '#27ae60' : '#999999');46 };47 render();48
49 text.on('pointerdown', () => {50 const on = localStorage.getItem(key) !== 'off';51 localStorage.setItem(key, on ? 'off' : 'on');52 render();53 });54 }2755}makeToggle(x, y, label, key)… 指定位置にトグルを1つ作る関数です。効果音用と BGM 用の2つを作ります。localStorage.getItem(key)… 保存された設定を読みます。'off'のときだけオフ、それ以外はオンとみなします。localStorage.setItem(key, ...)… クリックで設定を反転して保存します。次に開いたときも覚えています。render()… いまの設定を見た目(ON/OFF の文字と色)に反映します。
ゲーム画面で設定を見る
Section titled “ゲーム画面で設定を見る”設定を読み、オンのときだけ音を鳴らすようにします。BGM を再生するコードを書き換えます。
scenes/game-scene.js を変更する
Section titled “scenes/game-scene.js を変更する”1414}1515
1616create() {17 // 未設定なら ON。'off' と保存されているときだけ切る。18 this.sfxOn = localStorage.getItem('slingshot-sfx') !== 'off';19 this.bgmOn = localStorage.getItem('slingshot-bgm') !== 'off';20
1721 this.bgm = this.sound.add('bgm', { loop: true, volume: 0.4 });18 this.bgm.play();22 if (this.bgmOn) this.bgm.play();1923 // 画面を抜けるときに止めないと鳴り続ける。2024 this.events.once('shutdown', () => this.bgm.stop());156160const vy = (anchor.y - bird.y) * power;157161bird.setStatic(false);158162bird.setVelocity(vx, vy);159this.sound.play('launch');163if (this.sfxOn) this.sound.play('launch');160164
161165bird = null;162166birdsLeft -= 1;178182 this.pigsLeft -= 1;179183 this.score += 1000;180184 this.scoreText.setText('スコア: ' + this.score);181 this.sound.play('hit');185 if (this.sfxOn) this.sound.play('hit');182186}183187this.pendingRemoval.clear();効果音を鳴らす所(pointerup の中の発射音と、update の中の当たった音)も、設定を見てから鳴らすように直しています。
スタート画面で効果音・BGM のオン・オフを切り替えられ、その設定でゲームが始まります。 ブラウザを閉じても設定は覚えています。
これでパチンコ物理ゲームは完成です。おつかれさまでした! ゲームの中身を先に作り、 見た目や音を後から足す、という進め方も体験できました。
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”game
(画像などの、文字ではないファイルです。ZIP には入っています)(画像などの、文字ではないファイルです。ZIP には入っています)(画像などの、文字ではないファイルです。ZIP には入っています)(画像などの、文字ではないファイルです。ZIP には入っています)素材のクレジット=================
■ 絵文字画像 (1f426.png / 1f437.png / 1f4e6.png) Twemoji (https://github.com/jdecked/twemoji) グラフィックは CC-BY 4.0 (https://creativecommons.org/licenses/by/4.0/) © Twitter, Inc and other contributors - 1f426.png … 🐦 鳥(弾) / 1f437.png … 🐷 ブタ(標的) / 1f4e6.png … 📦 箱
■ 効果音 (launch.wav, hit.wav) Kenney Interface Sounds (https://kenney.nl) CC0 1.0(パブリックドメイン相当)。詳細は LICENSE.txt を参照。 - launch.wav … 発射の音 / hit.wav … ブタに当たった音
■ BGM (bgm.wav) 本教材用に用意したループ曲。CC0 1.0(パブリックドメイン相当)。
CC-BY 4.0 の条件により、画像の帰属表示(クレジット)を残しています。(画像などの、文字ではないファイルです。ZIP には入っています)(画像などの、文字ではないファイルです。ZIP には入っています)素材のライセンス=================
■ Twemoji graphics (1f426.png / 1f437.png / 1f4e6.png) Copyright Twitter, Inc and other contributors. https://github.com/jdecked/twemoji Licensed under CC-BY 4.0: https://creativecommons.org/licenses/by/4.0/
■ 効果音 (launch.wav, hit.wav) Kenney Interface Sounds — https://kenney.nl CC0 1.0 Universal (Public Domain Dedication): https://creativecommons.org/publicdomain/zero/1.0/ 帰属表示は不要ですが、感謝を込めてクレジットに記載しています。
■ BGM (bgm.wav) 本教材用に用意したループ曲。 CC0 1.0 Universal (Public Domain Dedication): https://creativecommons.org/publicdomain/zero/1.0/class ClearScene extends Phaser.Scene { constructor() { super('Clear'); }
create(data) { const score = data.score || 0;
this.add .text(360, 180, 'クリア!', { fontSize: '40px', color: '#2e7d32', fontStyle: 'bold', }) .setOrigin(0.5);
this.add .text(360, 250, 'スコア: ' + score, { fontSize: '28px', color: '#333333', }) .setOrigin(0.5);
this.add .text(360, 320, 'クリックでスタートに戻る', { fontSize: '18px', color: '#555555', }) .setOrigin(0.5);
this.input.once('pointerdown', () => this.scene.start('Start')); }}class GameScene extends Phaser.Scene { constructor() { super('Game'); }
preload() { // 素材は twemoji の絵文字画像。 this.load.image('bird', 'assets/1f426.png'); this.load.image('pig', 'assets/1f437.png'); this.load.image('block', 'assets/1f4e6.png'); this.load.audio('launch', 'assets/launch.wav'); this.load.audio('hit', 'assets/hit.wav'); this.load.audio('bgm', 'assets/bgm.wav'); }
create() { // 未設定なら ON。'off' と保存されているときだけ切る。 this.sfxOn = localStorage.getItem('slingshot-sfx') !== 'off'; this.bgmOn = localStorage.getItem('slingshot-bgm') !== 'off';
this.bgm = this.sound.add('bgm', { loop: true, volume: 0.4 }); if (this.bgmOn) this.bgm.play(); // 画面を抜けるときに止めないと鳴り続ける。 this.events.once('shutdown', () => this.bgm.stop());
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 .image(towerX, boxY, 'block') .setDisplaySize(boxSize, boxSize); this.matter.add.gameObject(box, { shape: { type: 'rectangle', width: boxSize, height: boxSize }, 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 .image(pos.x, pos.y, 'pig') .setDisplaySize(pigRadius * 2, pigRadius * 2); 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 .image(anchor.x, anchor.y, 'bird') .setDisplaySize(birdRadius * 2, birdRadius * 2); 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); if (this.sfxOn) this.sound.play('launch');
bird = null; birdsLeft -= 1; drawReserve();
this.time.delayedCall(1200, () => { if (birdsLeft > 0) { spawnBird(); } else { this.scene.start('GameOver', { score: this.score }); } }); }); }
update() { for (const pig of this.pendingRemoval) { pig.destroy(); this.pigsLeft -= 1; this.score += 1000; this.scoreText.setText('スコア: ' + this.score); if (this.sfxOn) this.sound.play('hit'); } this.pendingRemoval.clear();
// 何度も遷移しないよう、クリアは1回だけ。 if (!this.cleared && this.pigsLeft <= 0) { this.cleared = true; this.scene.start('Clear', { score: this.score }); } }}class GameOverScene extends Phaser.Scene { constructor() { super('GameOver'); }
create(data) { const score = data.score || 0;
this.add .text(360, 180, 'ゲームオーバー', { fontSize: '36px', color: '#c0392b', fontStyle: 'bold', }) .setOrigin(0.5);
this.add .text(360, 250, 'スコア: ' + score, { fontSize: '28px', color: '#333333', }) .setOrigin(0.5);
this.add .text(360, 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(360, 140, 'パチンコ物理ゲーム', { fontSize: '36px', color: '#5d4037', fontStyle: 'bold', }) .setOrigin(0.5);
const startText = this.add .text(360, 250, '▶ スタート', { 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(360, 350, '効果音', 'slingshot-sfx'); this.makeToggle(360, 410, 'BGM', 'slingshot-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>20 設定で音を切り替える</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],});