イベントハンドリング
04 章で、ゲームらしいルールがそろいました。ブタに当たったら消える、全部倒したらクリア、 撃ち切ったらゲームオーバー。よく見ると、どれも「何かが起きたら、何かをする」という同じ 形をしています。
ここからの 2 節は、また手を動かさない休憩です。この「起きたら、する」を Phaser がどう 扱っているのか、イベントとライフサイクルの 2 つに分けて見ます。まずイベントからです。
2 つのやり方 — 聞きに行く/教えてもらう
Section titled “2 つのやり方 — 聞きに行く/教えてもらう”「クリックされたら発射する」を作るとき、方法は 2 通りあります。
毎フレーム、聞きに行く(ポーリング)
update() { if (this.input.activePointer.isDown) { // 押されている「間」ずっと通る(1 秒に約 60 回) }}起きたら、教えてもらう(イベント)
create() { this.input.on('pointerdown', (pointer) => { // 押した「瞬間」に 1 回だけ通る });}違いは、if の中を何回通るかです。下のデモで、クリックしたり、押したままドラッグしたり
してみてください。2 つの数字がまったく違う伸び方をします。
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>イベントとポーリングの数え方</title> <style> body { margin: 0; padding: 16px; background: #fdf6e3; color: #333; font-family: system-ui, -apple-system, 'Hiragino Kaku Gothic ProN', sans-serif; display: grid; justify-items: center; gap: 12px; }
canvas { display: block; border: 2px solid #333; }
button { font: inherit; padding: 8px 18px; border: 2px solid #333; border-radius: 6px; background: #fff; cursor: pointer; }
button:hover { background: #f0e6cf; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script> <script src="main.js" defer></script> </head> <body> <div id="stage"></div> <button id="reset" type="button">0 に戻す</button> </body></html>// 同じ操作を 2 通りで数える。// イベント … pointerdown が起きた「回数」// ポーリング … update で isDown が true だった「フレーム数」class MainScene extends Phaser.Scene { constructor() { super('Main'); }
create() { this.downCount = 0; // イベントで数えた「押した回数」 this.frameCount = 0; // ポーリングで数えた「押されていたフレーム数」
this.add.text( 24, 20, 'この枠の中をクリック/押したままドラッグしてください', { fontSize: '15px', color: '#777777', }, );
// 起きたら、教えてもらう。押した「瞬間」に 1 回だけ通る。 this.input.on('pointerdown', () => { this.downCount += 1; });
this.add.text(40, 66, "イベント on('pointerdown')", { fontSize: '17px', color: '#2b6cb0', }); this.add.text(40, 151, 'ポーリング update の isDown', { fontSize: '17px', color: '#c0392b', });
this.eventText = this.add.text(430, 66, '', { fontSize: '17px', color: '#2b6cb0', }); this.pollText = this.add.text(430, 151, '', { fontSize: '17px', color: '#c0392b', });
// 伸び方の違いを、棒の長さでも見せる。 this.eventBar = this.add .rectangle(40, 110, 0, 20, 0x2b6cb0) .setOrigin(0, 0.5); this.pollBar = this.add .rectangle(40, 195, 0, 20, 0xc0392b) .setOrigin(0, 0.5); }
update() { // 毎フレーム、聞きに行く。押している「間」ずっと通る(1 秒に約 60 回)。 if (this.input.activePointer.isDown) this.frameCount += 1;
this.eventText.setText(this.downCount + ' 回'); this.pollText.setText(this.frameCount + ' フレーム');
this.eventBar.width = Math.min(this.downCount * 10, 604); this.pollBar.width = Math.min(this.frameCount * 10, 604); }
reset() { this.downCount = 0; this.frameCount = 0; }}
const game = new Phaser.Game({ type: Phaser.AUTO, parent: 'stage', width: 684, height: 240, backgroundColor: '#fdf6e3', scene: [MainScene],});
document.querySelector('#reset').addEventListener('click', () => { game.scene.getScene('Main').reset();});- ポーリング は「いま押されているか」という状態を聞いています。押しっぱなしなら、
ずっと
trueです。 - イベント は「押された」という出来事を受け取っています。押した瞬間に 1 回だけです。
パチンコで pointerdown を使ったのは、「押した瞬間に鳥を構え直す」が 1 回だけ起きてほしい
からです。ポーリングで書くと、押している間ずっと構え直すことになり、鳥がその場に固まります。
一方、「押している間ずっと力をためる」ようなゲームなら、ポーリングのほうが素直です。 瞬間をとらえたいならイベント、続いている状態を見たいならポーリング、が目安です。
イベントの 3 つの部品
Section titled “イベントの 3 つの部品”イベントを書くとき、必ず 3 つのことを決めています。
// 発生源.on('名前', ハンドラ)this.input.on('pointerdown', (pointer) => { bird.setPosition(pointer.x, pointer.y);});- 発生源 … 誰が知らせてくれるか。
this.input、this.matter.world、オブジェクト自身。 - 名前 … 何が起きたか。
'pointerdown'、'collisionstart'。 - ハンドラ … どうするか。あとから呼ばれる関数です。
3 つ目に注目してください。ハンドラも、自分では呼びません。用意しておくと、Phaser が
呼びます。create が「シーンが始まったら呼ばれる関数」であるのと同じで、ハンドラは
「その出来事が起きたら呼ばれる関数」です。用意しておくと、向こうから呼ばれる。 この形は
次の節でもう一度出てきます。
そして、ハンドラの引数には詳しい情報が届きます。pointer.x / pointer.y は
ゲーム画面の左上を原点にした座標でした(03 章 座標の考え方)。
だから、そのまま setPosition に渡せます。
下のデモは、届いたイベントをこの 3 列のまま並べています。押した場所に丸が飛ぶのは、
受け取った pointer をそのまま渡しているからです。
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>イベントの 3 つの部品</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="main.js" defer></script> </head> <body></body></html>// イベントは「発生源・名前・ハンドラ」の 3 点セット。// 届いたものをそのまま 3 列に並べて、誰から何が来たのかを見比べる。class MainScene extends Phaser.Scene { constructor() { super('Main'); }
create() { this.rows = [];
this.add.text( 20, 16, '左の白い板をクリック/ドラッグ。オレンジのボタンも押せます。', { fontSize: '14px', color: '#777777', }, );
// 遊ぶ場所。 this.add .rectangle(20, 44, 336, 262, 0xffffff) .setOrigin(0) .setStrokeStyle(2, 0xcccccc); this.bird = this.add .circle(188, 180, 16, 0xffffff) .setStrokeStyle(3, 0x333333);
// 発生源 ①:画面全体(this.input)。どこを押しても届く。 this.input.on('pointerdown', (pointer) => { // ハンドラの引数に詳しい情報が届く。ゲーム画面の左上が原点なので、そのまま渡せる。 this.bird.setPosition(pointer.x, pointer.y); this.log( 'this.input', 'pointerdown', 'pointer = (' + this.xy(pointer) + ')', ); });
this.input.on('pointerup', (pointer) => { this.log( 'this.input', 'pointerup', 'pointer = (' + this.xy(pointer) + ')', ); });
// 発生源 ②:部品そのもの。この四角を押したときだけ届く。 const button = this.add .rectangle(188, 268, 150, 40, 0xe08e3c) .setStrokeStyle(3, 0x333333); this.add .text(188, 268, 'ボタン', { fontSize: '17px', color: '#ffffff' }) .setOrigin(0.5);
button.setInteractive({ useHandCursor: true }); button.on('pointerdown', () => this.log('button', 'pointerdown', 'この部品だけに届く'), ); button.on('pointerover', () => this.log('button', 'pointerover', 'カーソルが乗った'), );
// 受け取ったイベントの表示欄。 this.add .rectangle(372, 44, 332, 262, 0xffffff) .setOrigin(0) .setStrokeStyle(2, 0xcccccc); this.add.text( 384, 54, '発生源'.padEnd(12) + '名前'.padEnd(12) + 'ハンドラの引数', { fontSize: '12px', color: '#777777', fontFamily: 'ui-monospace, Menlo, monospace', }, ); this.logText = this.add.text(384, 78, '', { fontSize: '12px', color: '#333333', lineSpacing: 6, fontFamily: 'ui-monospace, Menlo, monospace', }); }
xy(pointer) { return Math.round(pointer.x) + ', ' + Math.round(pointer.y); }
log(source, name, detail) { this.rows.unshift(source.padEnd(12) + name.padEnd(13) + detail); if (this.rows.length > 11) this.rows.pop(); this.logText.setText(this.rows); }}
new Phaser.Game({ type: Phaser.AUTO, width: 720, height: 320, backgroundColor: '#fdf6e3', scene: [MainScene],});ブラウザのイベントと同じ形
Section titled “ブラウザのイベントと同じ形”この形は Phaser が発明したものではありません。ブラウザにもともとある考え方です。
// ブラウザbutton.addEventListener('click', (event) => { /* ... */});
// Phaserthis.input.on('pointerdown', (pointer) => { /* ... */});名前が addEventListener か on かの違いだけで、構造は同じです。Node.js の emitter.on(...)、
Vue の @click、React の onClick も同じ発想です。イベントは、特定のフレームワークの機能
ではなく、Web 全体で共通の考え方だと思ってかまいません。ひとつ覚えれば、だいたい通用します。
左は Phaser をまったく使っていない、素の HTML のボタンです。並べてみると、登録している行が 同じ形をしているのが分かります。
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>ブラウザのイベントと Phaser のイベント</title> <style> body { margin: 0; padding: 16px; background: #fdf6e3; color: #333; font-family: system-ui, -apple-system, 'Hiragino Kaku Gothic ProN', sans-serif; display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.panel { display: grid; justify-items: center; align-content: start; gap: 10px; padding: 12px; border: 2px solid #333; border-radius: 8px; background: #fff; }
h2 { margin: 0; font-size: 15px; }
code { font-size: 12px; color: #2b6cb0; word-break: break-all; text-align: center; }
canvas { display: block; }
#dom-button { font: inherit; width: 150px; height: 52px; border: 3px solid #333; border-radius: 6px; background: #e08e3c; color: #fff; cursor: pointer; }
p { margin: 0; font-size: 15px; }
b { font-size: 20px; color: #c0392b; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script> <script src="main.js" defer></script> </head> <body> <section class="panel"> <h2>ブラウザ(素の HTML)</h2> <code>button.addEventListener('click', …)</code> <button id="dom-button" type="button">押す</button> <p>押した回数 <b id="dom-count">0</b> 回</p> </section>
<section class="panel"> <h2>Phaser</h2> <code>this.input.on('pointerdown', …)</code> <div id="stage"></div> <p>押した回数 <b id="phaser-count">0</b> 回</p> </section> </body></html>// 左はブラウザ、右は Phaser。登録の仕方が同じ形をしていることを見る。
// --- ブラウザ側 -----------------------------------------------------------let domCount = 0;
// 発生源.addEventListener('名前', ハンドラ)document.querySelector('#dom-button').addEventListener('click', (event) => { domCount += 1; document.querySelector('#dom-count').textContent = domCount;});
// --- Phaser 側 ------------------------------------------------------------class MainScene extends Phaser.Scene { constructor() { super('Main'); }
create() { this.count = 0;
const target = this.add.rectangle(150, 76, 150, 52, 0xe08e3c); target.setStrokeStyle(3, 0x333333); this.add .text(150, 76, '押す', { fontSize: '16px', color: '#ffffff' }) .setOrigin(0.5);
// 発生源.on('名前', ハンドラ) this.input.on('pointerdown', (pointer) => { this.count += 1; document.querySelector('#phaser-count').textContent = this.count; }); }}
new Phaser.Game({ type: Phaser.AUTO, parent: 'stage', width: 300, height: 152, backgroundColor: '#fdf6e3', scene: [MainScene],});このゲームで使ったイベント
Section titled “このゲームで使ったイベント”| 名前 | 発生源 | 使った場所 |
|---|---|---|
pointerdown |
this.input(画面全体) |
02 章 04 クリックで飛ばす / 05 引っ張り始め |
pointermove |
this.input |
02 章 05 引っ張っている間の位置更新 |
pointerup |
this.input |
02 章 05 離して発射 |
pointerdown |
startText(部品そのもの) |
02 章 08 スタート画面のボタン |
collisionstart |
this.matter.world(物理エンジン) |
04 章 02 当たったブタを消す |
発生源が 3 種類あることに気づきます。画面全体・部品ひとつ・エンジン。 これは 03 章 で見た「誰が何を 持っているか」がそのまま出ています。イベントは、その持ち主から出てくるのです。
下は、この 4 つだけを取り出した小さなパチンコです。鳥を引っ張って離すと、どのイベントが
いつ発火しているかがランプで分かります。pointermove が、引っ張っていないときも
ずっと光り続けることに注目してください。だからハンドラの先頭に if (!dragging) return; が
要るわけです。
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>このゲームで使ったイベント</title> <style> body { margin: 0; padding: 16px; background: #fdf6e3; color: #333; font-family: system-ui, -apple-system, 'Hiragino Kaku Gothic ProN', sans-serif; display: grid; justify-items: center; gap: 12px; }
canvas { display: block; border: 2px solid #333; }
button { font: inherit; padding: 8px 18px; border: 2px solid #333; border-radius: 6px; background: #fff; cursor: pointer; }
button:hover { background: #f0e6cf; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script> <script src="main.js" defer></script> </head> <body> <div id="stage"></div> <button id="restart" type="button">箱を積み直す</button> </body></html>// 小さくしたパチンコ。02〜04 章で使った 4 つのイベントが発火するたび、右のランプが光る。const GAME_WIDTH = 440; // 左側がゲーム。右側はランプの表示欄。const NAMES = ['pointerdown', 'pointermove', 'pointerup', 'collisionstart'];
class MainScene extends Phaser.Scene { constructor() { super('Main'); }
create() { this.counts = { pointerdown: 0, pointermove: 0, pointerup: 0, collisionstart: 0, }; this.lit = { pointerdown: 0, pointermove: 0, pointerup: 0, collisionstart: 0, };
// ゲームの外へ飛び出さないよう、物理の世界を左半分だけにする。 this.matter.world.setBounds(0, 0, GAME_WIDTH, 340);
const groundY = 315; const groundHeight = 50; const groundTop = groundY - groundHeight / 2; // 地面の上面。物はこの高さに乗る
const ground = this.add.rectangle( GAME_WIDTH / 2, groundY, GAME_WIDTH, groundHeight, 0x888888, ); this.matter.add.gameObject(ground, { isStatic: true });
for (let i = 0; i < 3; i++) { const box = this.add.rectangle( 365, groundTop - 16 - i * 32, 32, 32, 0xdddddd, ); box.setStrokeStyle(3, 0x333333); this.matter.add.gameObject(box, { restitution: 0.1 }); }
const anchor = { x: 110, y: 210 }; this.add.circle(anchor.x, anchor.y, 5, 0xbbbbbb);
const bird = this.add .circle(anchor.x, anchor.y, 14, 0xffffff) .setStrokeStyle(3, 0x333333); this.matter.add.gameObject(bird, { shape: { type: 'circle', radius: 14 }, restitution: 0.2, }); bird.setStatic(true);
let dragging = false;
// ①〜③ 発生源は this.input(画面全体)。 this.input.on('pointerdown', (pointer) => { this.fire('pointerdown'); if (pointer.x > GAME_WIDTH) return; bird.setStatic(true); bird.setPosition(anchor.x, anchor.y); bird.setVelocity(0, 0); dragging = true; });
this.input.on('pointermove', (pointer) => { // 動かしている間ずっと発火する。だからハンドラの先頭で「今いるかどうか」を確かめる。 this.fire('pointermove'); if (!dragging) return; const dx = pointer.x - anchor.x; const dy = pointer.y - anchor.y; const dist = Math.hypot(dx, dy); const scale = dist > 80 ? 80 / dist : 1; bird.setPosition(anchor.x + dx * scale, anchor.y + dy * scale); });
this.input.on('pointerup', () => { this.fire('pointerup'); if (!dragging) return; dragging = false; bird.setStatic(false); bird.setVelocity((anchor.x - bird.x) * 0.22, (anchor.y - bird.y) * 0.22); });
// ④ 発生源は物理エンジン(this.matter.world)。ぶつかった瞬間に届く。 this.matter.world.on('collisionstart', () => this.fire('collisionstart'));
this.buildPanel(); }
/** ランプを光らせて、回数を 1 増やす。 */ fire(name) { this.counts[name] += 1; this.lit[name] = 12; // 12 フレームだけ点灯させる }
buildPanel() { this.add .rectangle(GAME_WIDTH + 14, 20, 222, 300, 0xffffff) .setOrigin(0) .setStrokeStyle(2, 0xcccccc); this.add.text(GAME_WIDTH + 28, 34, '発火したイベント', { fontSize: '13px', color: '#777777', });
this.lamps = {}; this.labels = {}; NAMES.forEach((name, i) => { const y = 74 + i * 62; this.lamps[name] = this.add .circle(GAME_WIDTH + 40, y, 9, 0xdddddd) .setStrokeStyle(2, 0x999999); this.add.text(GAME_WIDTH + 58, y - 9, name, { fontSize: '13px', color: '#333333', }); this.labels[name] = this.add.text(GAME_WIDTH + 58, y + 8, '', { fontSize: '12px', color: '#777777', }); });
this.add.text(GAME_WIDTH + 28, 300, '鳥を引っ張って離してみてください', { fontSize: '11px', color: '#777777', }); }
update() { for (const name of NAMES) { if (this.lit[name] > 0) this.lit[name] -= 1; this.lamps[name].setFillStyle(this.lit[name] > 0 ? 0xe08e3c : 0xdddddd); this.labels[name].setText(this.counts[name] + ' 回'); } }}
const game = new Phaser.Game({ type: Phaser.AUTO, parent: 'stage', width: 684, height: 340, backgroundColor: '#fdf6e3', physics: { default: 'matter', matter: { gravity: { y: 1 } }, }, scene: [MainScene],});
document.querySelector('#restart').addEventListener('click', () => { game.scene.getScene('Main').scene.restart();});画面全体か、その部品か
Section titled “画面全体か、その部品か”同じ pointerdown でも、どこに登録するかで意味が変わります。
// 画面のどこを押しても反応するthis.input.on('pointerdown', () => { /* ... */});
// その部品を押したときだけ反応するstartText.setInteractive({ useHandCursor: true });startText.on('pointerdown', () => this.scene.start('Game'));setInteractive() は「このオブジェクトは、押される対象です」という宣言です。Phaser は、
置かれたオブジェクト全部の当たり判定を毎回調べたりはしません。宣言したものだけを調べます。
そのため、setInteractive() を忘れると、on('pointerdown', ...) をいくら書いても
何も起きません。エラーも出ないので、はじめのうちは必ず一度はまります。ボタンが反応しない
ときは、まずここを見てください。
useHandCursor: true は、その上にマウスを載せたときにカーソルを指の形にする指定です。
「押せます」と見た目で伝えるための、ちょっとした親切です。
下のデモでは、setInteractive() を後から外せます。外した状態でボタンを押してみてください。
画面全体のカウンタだけが増えて、ボタンのカウンタは止まったままになります。
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>画面全体か、その部品か</title> <style> body { margin: 0; padding: 16px; background: #fdf6e3; color: #333; font-family: system-ui, -apple-system, 'Hiragino Kaku Gothic ProN', sans-serif; display: grid; justify-items: center; gap: 12px; }
canvas { display: block; border: 2px solid #333; }
button { font: inherit; padding: 8px 18px; border: 2px solid #333; border-radius: 6px; background: #fff; cursor: pointer; }
button:hover { background: #f0e6cf; }
.hint { margin: 0; font-size: 13px; color: #777; text-align: center; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script> <script src="main.js" defer></script> </head> <body> <div id="stage"></div> <button id="toggle" type="button">setInteractive() を外す</button> <p class="hint"> 外した状態でもオレンジの四角は押せます。ただし「ボタンの回数」だけが増えなくなります。<br /> エラーは出ません。ボタンが無反応なときは、まずここを疑ってください。 </p> </body></html>// 同じ 'pointerdown' でも、どこに登録するかで意味が変わる。// さらに setInteractive() を外すと、部品側だけが無言で反応しなくなる。class MainScene extends Phaser.Scene { constructor() { super('Main'); }
create() { this.screenCount = 0; this.buttonCount = 0;
this.screenText = this.add.text(330, 76, '', { fontSize: '18px', color: '#2b6cb0', }); this.buttonText = this.add.text(330, 116, '', { fontSize: '18px', color: '#c0392b', }); this.stateText = this.add.text(330, 166, '', { fontSize: '15px', color: '#777777', });
// 画面のどこを押しても反応する。 this.input.on('pointerdown', () => { this.screenCount += 1; this.render(); });
this.button = this.add .rectangle(150, 120, 190, 62, 0xe08e3c) .setStrokeStyle(3, 0x333333); this.add .text(150, 120, 'ボタン', { fontSize: '20px', color: '#ffffff' }) .setOrigin(0.5);
// その部品を押したときだけ反応する。 this.button.on('pointerdown', () => { this.buttonCount += 1; this.render(); });
// 「この部品は押される対象です」と宣言する。これが無いと上の on(...) は呼ばれない。 this.applyInteractive(true); }
/** setInteractive() を付けたり外したりする。 */ applyInteractive(on) { this.isDeclared = on; if (on) this.button.setInteractive({ useHandCursor: true }); else this.button.disableInteractive(); this.render(); }
render() { this.screenText.setText( '画面全体 this.input … ' + this.screenCount + ' 回', ); this.buttonText.setText( 'ボタン button … ' + this.buttonCount + ' 回', ); this.stateText.setText( this.isDeclared ? 'いま: setInteractive() あり' : 'いま: setInteractive() なし', ); }}
const game = new Phaser.Game({ type: Phaser.AUTO, parent: 'stage', width: 684, height: 230, backgroundColor: '#fdf6e3', scene: [MainScene],});
document.querySelector('#toggle').addEventListener('click', (event) => { const scene = game.scene.getScene('Main'); const next = !scene.isDeclared; scene.applyInteractive(next); event.target.textContent = next ? 'setInteractive() を外す' : 'setInteractive() を付ける';});1 回だけ受け取る
Section titled “1 回だけ受け取る”結果画面では、on ではなく once を使っていました。
this.input.once('pointerdown', () => this.scene.start('Start'));once は「1 回受け取ったら、自動で登録を外す」という指定です。結果画面は 1 回クリックされたら
スタート画面に戻るだけなので、2 回目以降は必要ありません。連打で二重に切り替わる事故も防げます。
下のデモは、同じ pointerdown に on と once を 1 つずつ登録しています。連打すると、
once のほうだけが 1 で止まり、登録されているハンドラの数も 1 つ減ります。
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>on と once</title> <style> body { margin: 0; padding: 16px; background: #fdf6e3; color: #333; font-family: system-ui, -apple-system, 'Hiragino Kaku Gothic ProN', sans-serif; display: grid; justify-items: center; gap: 12px; }
canvas { display: block; border: 2px solid #333; }
button { font: inherit; padding: 8px 18px; border: 2px solid #333; border-radius: 6px; background: #fff; cursor: pointer; }
button:hover { background: #f0e6cf; }
.hint { margin: 0; font-size: 13px; color: #777; text-align: center; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script> <script src="main.js" defer></script> </head> <body> <div id="stage"></div> <button id="restart" type="button">登録しなおす(シーンをやり直す)</button> <p class="hint"> 同じ 'pointerdown' に、on と once で 1 つずつハンドラを登録しています。 </p> </body></html>// 同じイベントに on と once を 1 つずつ登録して、連打してみる。class MainScene extends Phaser.Scene { constructor() { super('Main'); }
create() { this.onCount = 0; this.onceCount = 0;
this.add.text(24, 18, 'この枠の中を何度もクリックしてください', { fontSize: '15px', color: '#777777', });
// on … 受け取り続ける。外すまでずっと呼ばれる。 this.input.on('pointerdown', () => { this.onCount += 1; this.render(); });
// once … 1 回受け取ったら、自動で登録が外れる。 this.input.once('pointerdown', () => { this.onceCount += 1; this.render(); });
// 登録し終えた時点のハンドラ数を覚えておく(あとで減ったことを見せるため)。 this.registered = this.input.listenerCount('pointerdown');
this.onText = this.add.text(60, 78, '', { fontSize: '20px', color: '#2b6cb0', }); this.onceText = this.add.text(60, 126, '', { fontSize: '20px', color: '#c0392b', }); this.aliveText = this.add.text(60, 172, '', { fontSize: '14px', color: '#777777', }); this.render(); }
render() { this.onText.setText( "on('pointerdown', …) … " + this.onCount + ' 回 呼ばれた', ); this.onceText.setText( "once('pointerdown', …) … " + this.onceCount + ' 回 呼ばれた', );
// once のハンドラがまだ残っているかを、Phaser に聞いてみる。 const remaining = this.input.listenerCount('pointerdown'); this.aliveText.setText( 'pointerdown に登録されているハンドラ … ' + remaining + ' 個' + (remaining < this.registered ? '(once の分が自動で外れた)' : ''), ); }}
const game = new Phaser.Game({ type: Phaser.AUTO, parent: 'stage', width: 684, height: 210, backgroundColor: '#fdf6e3', scene: [MainScene],});
document.querySelector('#restart').addEventListener('click', () => { game.scene.getScene('Main').scene.restart();});登録は create で 1 回だけ
Section titled “登録は create で 1 回だけ”ここで効いてくるのが、コードを書く場所です。create は画面ができたときに 1 回だけ、
update は毎フレーム呼ばれる場所でした。
// 悪い例:登録を update に書いてしまったupdate() { this.input.on('pointerdown', () => { this.score += 1; });}update は毎フレーム呼ばれます。つまり、1 秒間に約 60 個のハンドラが登録されます。
10 秒放置してから 1 回クリックすると、スコアが 600 増えます。
このバグのいやらしいところは、エラーが出ないことです。動くには動く。ただ「なんだか多く 入る」だけ。しかも放置した時間によって増え方が変わるので、再現もしにくい。
下のデモで、実際に体験できます。悪い例に切り替えたら、しばらく放置してから 1 回だけ クリックしてみてください。放置した秒数 × 60 くらいの点が、一度に入ります。
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>登録は create で 1 回だけ</title> <style> body { margin: 0; padding: 16px; background: #fdf6e3; color: #333; font-family: system-ui, -apple-system, 'Hiragino Kaku Gothic ProN', sans-serif; display: grid; justify-items: center; gap: 12px; }
canvas { display: block; border: 2px solid #333; }
button { font: inherit; padding: 8px 18px; border: 2px solid #333; border-radius: 6px; background: #fff; cursor: pointer; }
button:hover { background: #f0e6cf; }
.hint { margin: 0; font-size: 13px; color: #777; text-align: center; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script> <script src="main.js" defer></script> </head> <body> <div id="stage"></div> <button id="toggle" type="button"> update に登録する(悪い例)に切り替える </button> <p class="hint"> 悪い例に切り替えたら、しばらく放置してから 1 回だけクリックしてみてください。<br /> 放置した時間が長いほど、1 回のクリックでスコアが大きく増えます。エラーは出ません。 </p> </body></html>// イベントの登録を create に書いた場合と、update に書いてしまった場合を比べる。// update は毎フレーム呼ばれるので、書く場所を間違えるとハンドラが積み上がっていく。const LIMIT = 600; // ブラウザが固まらないよう、このデモでは 600 個で打ち止めにする
class MainScene extends Phaser.Scene { constructor() { super('Main'); }
create() { this.mode = 'create'; // 'create' か 'update' this.score = 0; this.lastScore = 0; this.lastGain = 0;
this.add.text(24, 18, 'この枠の中をクリックするとスコアが増えます', { fontSize: '15px', color: '#777777', });
this.info = this.add.text(40, 60, '', { fontSize: '18px', color: '#333333', lineSpacing: 12, });
// 登録は create で 1 回だけ。これが正しい書き方。 this.input.on('pointerdown', this.bump, this); }
bump() { this.score += 1; }
/** create に登録するモードと、update に登録するモードを切り替える。 */ setMode(mode) { this.mode = mode; this.score = 0; this.lastScore = 0; this.lastGain = 0;
// いったん全部外してから、create モードのときだけ 1 個だけ登録し直す。 this.input.off('pointerdown'); if (mode === 'create') this.input.on('pointerdown', this.bump, this); }
update() { // 悪い例:毎フレーム登録してしまう。1 秒あたり約 60 個ずつ増えていく。 if ( this.mode === 'update' && this.input.listenerCount('pointerdown') < LIMIT ) { this.input.on('pointerdown', this.bump, this); }
// 直前のクリックで何点入ったかを、スコアの増え方から割り出す。 if (this.score !== this.lastScore) { this.lastGain = this.score - this.lastScore; this.lastScore = this.score; }
const handlers = this.input.listenerCount('pointerdown'); this.info.setText([ '書いた場所 … ' + (this.mode === 'create' ? 'create(1 回だけ)' : 'update(毎フレーム)'), '登録されたハンドラ … ' + handlers + ' 個' + (handlers >= LIMIT ? '(打ち止め)' : ''), '直前の 1 クリックで … ' + this.lastGain + ' 点ふえた', 'スコア合計 … ' + this.score, ]); }}
const game = new Phaser.Game({ type: Phaser.AUTO, parent: 'stage', width: 684, height: 250, backgroundColor: '#fdf6e3', scene: [MainScene],});
document.querySelector('#toggle').addEventListener('click', (event) => { const scene = game.scene.getScene('Main'); const next = scene.mode === 'create' ? 'update' : 'create'; scene.setMode(next); event.target.textContent = next === 'update' ? 'create に登録する(正しい)に戻す' : 'update に登録する(悪い例)に切り替える';});覚え方はかんたんです。登録は create、判断は update。
create() { this.input.on('pointerdown', () => { this.wantsLaunch = true; }); // 登録は 1 回}
update() { if (this.wantsLaunch) { /* ... */ } // 判断は毎フレーム}すぐにやらない、という選択
Section titled “すぐにやらない、という選択”04 章 当たったブタを消す では、 少し変わった書き方をしていました。
this.matter.world.on('collisionstart', (event) => { // ここでは「消す予約」だけをする if (a.isBird && b.isPig) this.pendingRemoval.add(b);});
update() { // 実際に消すのは、毎フレームのここ for (const pig of this.pendingRemoval) pig.destroy(); this.pendingRemoval.clear();}なぜ、ぶつかった瞬間に消さないのでしょうか。
collisionstart は、物理エンジンが計算している最中に呼ばれます。エンジンが「いま、この
2 つがぶつかっている」と処理している途中で、その片方を消してしまうと、エンジンが足元を
すくわれます。だから「予約」だけしておいて、計算が終わったあとの update でまとめて消します。
下のデモは、そのタイミングを目に見えるようにしたものです。ログの「物理計算中」の列に注目
してください。collisionstart が届いた行ははい、update で消している行はいいえに
なります。フレーム番号も 1 つずれます。予約したものが実際に消えるのは、次のフレームです。
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>すぐにやらない、という選択</title> <style> body { margin: 0; padding: 16px; background: #fdf6e3; color: #333; font-family: system-ui, -apple-system, 'Hiragino Kaku Gothic ProN', sans-serif; display: grid; justify-items: center; gap: 12px; }
canvas { display: block; border: 2px solid #333; }
button { font: inherit; padding: 8px 18px; border: 2px solid #333; border-radius: 6px; background: #fff; cursor: pointer; }
button:hover { background: #f0e6cf; }
.hint { margin: 0; font-size: 13px; color: #777; text-align: center; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script> <script src="main.js" defer></script> </head> <body> <div id="stage"></div> <button id="toggle" type="button">「その場で消す」に切り替える</button> <p class="hint"> 左側をクリックすると、その位置に鳥が落ちてきます。右のログで順番を見てください。 </p> </body></html>// collisionstart は「物理エンジンが計算している最中」に呼ばれる。// そのことを、計算中かどうかの旗を立てて目に見えるようにした。const GAME_WIDTH = 410; // 左側がゲーム。右側はログ。
class MainScene extends Phaser.Scene { constructor() { super('Main'); }
create() { this.mode = 'later'; // 'later'(予約して update で消す)か 'now'(その場で消す) this.frames = 0; this.inPhysics = false; // いま物理エンジンの計算中か this.pending = new Set(); // 消す予約 this.lines = [];
this.matter.world.setBounds(0, 0, GAME_WIDTH, 340);
// 物理エンジンの計算が「始まった/終わった」を旗にする。 this.matter.world.on('beforeupdate', () => { this.inPhysics = true; }); this.matter.world.on('afterupdate', () => { this.inPhysics = false; });
const groundY = 315; const groundHeight = 50; const groundTop = groundY - groundHeight / 2; // 地面の上面。物はこの高さに乗る
const ground = this.add.rectangle( GAME_WIDTH / 2, groundY, GAME_WIDTH, groundHeight, 0x888888, ); this.matter.add.gameObject(ground, { isStatic: true });
for (let i = 0; i < 3; i++) { const pig = this.add.circle(105 + i * 100, groundTop - 20, 20, 0xf0b6c8); pig.setStrokeStyle(3, 0x333333); pig.setData('kind', 'pig'); this.matter.add.gameObject(pig, { shape: { type: 'circle', radius: 20 }, }); }
this.input.on('pointerdown', (pointer) => { if (pointer.x > GAME_WIDTH) return; const bird = this.add.circle(pointer.x, 30, 15, 0xffffff); bird.setStrokeStyle(3, 0x333333); bird.setData('kind', 'bird'); this.matter.add.gameObject(bird, { shape: { type: 'circle', radius: 15 }, }); });
this.matter.world.on('collisionstart', (event) => { for (const pair of event.pairs) { const objects = [pair.bodyA.gameObject, pair.bodyB.gameObject]; const pig = objects.find( (o) => o && o.getData && o.getData('kind') === 'pig', ); const bird = objects.find( (o) => o && o.getData && o.getData('kind') === 'bird', ); if (!pig || !bird || this.pending.has(pig)) continue;
this.log('collisionstart で 1 個みつけた'); if (this.mode === 'now') { // 計算中に消してしまう書き方。 pig.destroy(); this.log('→ その場で destroy した'); } else { // 状態を書き換えるだけにして、実際に消すのは次のフレームに回す。 this.pending.add(pig); this.log('→ 消す予約だけした'); } } });
this.buildPanel(); }
buildPanel() { this.add .rectangle(GAME_WIDTH + 12, 16, 250, 308, 0xffffff) .setOrigin(0) .setStrokeStyle(2, 0xcccccc); this.add.text(GAME_WIDTH + 24, 26, 'フレーム 物理計算中 できごと', { fontSize: '11px', color: '#777777', fontFamily: 'ui-monospace, Menlo, monospace', }); this.logText = this.add.text(GAME_WIDTH + 24, 48, '', { fontSize: '11px', color: '#333333', lineSpacing: 6, fontFamily: 'ui-monospace, Menlo, monospace', wordWrap: { width: 226 }, }); }
log(message) { const flag = this.inPhysics ? 'はい' : 'いいえ'; this.lines.unshift( String(this.frames).padStart(6) + ' ' + flag.padEnd(6) + message, ); if (this.lines.length > 14) this.lines.pop(); this.logText.setText(this.lines); }
update() { this.frames += 1;
// 計算が終わったあとの、安全なタイミングでまとめて消す。 if (this.pending.size > 0) { const n = this.pending.size; for (const pig of this.pending) pig.destroy(); this.pending.clear(); this.log('update で ' + n + ' 個 destroy した'); } }}
const game = new Phaser.Game({ type: Phaser.AUTO, parent: 'stage', width: 684, height: 340, backgroundColor: '#fdf6e3', physics: { default: 'matter', matter: { gravity: { y: 1 } }, }, scene: [MainScene],});
document.querySelector('#toggle').addEventListener('click', (event) => { const scene = game.scene.getScene('Main'); scene.mode = scene.mode === 'later' ? 'now' : 'later'; event.target.textContent = scene.mode === 'now' ? '「予約して update で消す」に戻す' : '「その場で消す」に切り替える';});イベントの中では、状態を書き換えるだけにして、重い処理や消す処理は次のフレームに回す。 ゲームに限らず、イベント駆動のコードでよく出てくる型です。
片付けはどうなるのか
Section titled “片付けはどうなるのか”シーンを離れるとき、そのシーンに登録したイベントは Phaser が片付けてくれます。だから、 この教材では一度も「イベントを外す」コードを書いていません。
ただし、どこまで自動で片付くかはフレームワークごとに違います。ブラウザの
addEventListener は、外すのは自分の仕事です。React のように「登録したら、去るときに自分で
外す」と決まっているものもあります(次の節で見ます)。
下のデモは、その差をそのまま見せています。「シーンをやり直す」を何回か押してから 1 回だけ
クリックしてください。Phaser 側は何回やり直しても +1 のままですが、自分でつけた
addEventListener は、やり直した回数だけ反応します。
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>登録したものは、誰が外すのか</title> <style> body { margin: 0; padding: 16px; background: #fdf6e3; color: #333; font-family: system-ui, -apple-system, 'Hiragino Kaku Gothic ProN', sans-serif; display: grid; justify-items: center; gap: 12px; }
canvas { display: block; border: 2px solid #333; }
.buttons { display: flex; gap: 10px; }
button { font: inherit; padding: 8px 18px; border: 2px solid #333; border-radius: 6px; background: #fff; cursor: pointer; }
button:hover { background: #f0e6cf; }
.hint { margin: 0; font-size: 13px; color: #777; text-align: center; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script> <script src="main.js" defer></script> </head> <body> <div id="stage"></div> <div class="buttons"> <button id="restart" type="button">シーンをやり直す</button> <button id="reload" type="button">最初から</button> </div> <p class="hint"> 「シーンをやり直す」を何回か押してから、枠の中を 1 回クリックしてください。<br /> Phaser 側は 1 回しか反応しませんが、自分でつけた DOM のハンドラは押した回数だけ反応します。 </p> </body></html>// シーンを何度もやり直して、「登録したものを誰が外すのか」を見る。// シーンが作り直されても残る数字なので、シーンの外に置いている。let starts = 0; // create が呼ばれた回数let phaserFires = 0; // Phaser 側のハンドラが呼ばれた回数let domFires = 0; // 自分で addEventListener したハンドラが呼ばれた回数let domHandlers = 0; // 自分でつけた DOM ハンドラの数(DOM には個数を聞けないので自分で数える)
const stage = document.querySelector('#stage');
class MainScene extends Phaser.Scene { constructor() { super('Main'); }
create() { starts += 1; this.lastPhaser = phaserFires; this.lastDom = domFires; this.gainPhaser = 0; this.gainDom = 0;
this.add.text(24, 18, 'この枠の中をクリックしてください', { fontSize: '15px', color: '#777777', });
// Phaser 側:シーンを離れるとき、Phaser が自動で外してくれる。 this.input.on('pointerdown', () => { phaserFires += 1; });
// ブラウザ側:外すのは自分の仕事。ここでは、わざと外さずに積み上げていく。 stage.addEventListener('click', () => { domFires += 1; }); domHandlers += 1;
this.info = this.add.text(40, 58, '', { fontSize: '17px', color: '#333333', lineSpacing: 11, }); }
update() { // 直前の 1 クリックで、それぞれ何回呼ばれたかを割り出す。 if (phaserFires !== this.lastPhaser || domFires !== this.lastDom) { this.gainPhaser = phaserFires - this.lastPhaser; this.gainDom = domFires - this.lastDom; this.lastPhaser = phaserFires; this.lastDom = domFires; }
this.info.setText([ 'シーンを作り直した回数 … ' + starts + ' 回', 'Phaser の pointerdown ハンドラ … ' + this.input.listenerCount('pointerdown') + ' 個(古い分は片付いた)', '自分でつけた click ハンドラ … ' + domHandlers + ' 個(外していないので残っている)', '', '直前の 1 クリックで … Phaser +' + this.gainPhaser + ' / DOM +' + this.gainDom, ]); }}
const game = new Phaser.Game({ type: Phaser.AUTO, parent: 'stage', width: 684, height: 240, backgroundColor: '#fdf6e3', scene: [MainScene],});
document.querySelector('#restart').addEventListener('click', () => { game.scene.getScene('Main').scene.restart();});
document .querySelector('#reload') .addEventListener('click', () => location.reload());新しいフレームワークを触るときは、「登録したものは、誰が、いつ外すのか」をドキュメントで 確認しておくと、あとで「なぜか二重に反応する」に悩まずにすみます。これも結局、 そのフレームワークの流れに乗るという話です。
- ポーリングは状態を聞きに行く、イベントは出来事を受け取る。瞬間をとらえたいなら イベント。
- イベントは「発生源・名前・ハンドラ」の 3 点セット。ブラウザでも Phaser でも形は同じ。
- ハンドラは自分では呼ばない。登録は
createで 1 回だけ、判断はupdate。 - 部品そのものを押させたいときは
setInteractive()。忘れると、無言で反応しなくなる。 - イベントの中では書き換えだけにして、消す処理は
updateに回すと安全。
this.input.on(...) も collisionstart も、正体は「用意しておくと呼ばれる関数」でした。
では、その create や update そのものは、誰が、いつ呼んでいるのでしょうか。次の節では、
その呼ばれる順番(ライフサイクル)を見ます。