Typewriter (タイプライター)
Phaser 3を使って、テキストを一文字ずつ表示する演出(タイプライターエフェクト)を作成します。 会話シーンやメッセージログなどでよく使われる表現です。
実際の動作を以下のキャンバスで確認できます。 再読み込みするにはページをリロードしてください。
コードスニペット
Section titled “コードスニペット”1. メソッド (Method)
Section titled “1. メソッド (Method)”このヘルパーメソッドを、 Scene クラスに追加してください。
/** * テキストを1文字ずつ表示するヘルパーメソッド * @param label 対象のテキストオブジェクト * @param text 表示する全文 * @param delay 文字ごとの表示間隔(ms) デフォルト: 100ms */public typewriteText(label: Phaser.GameObjects.Text, text: string, delay: number = 100) { const length = text.length; let i = 0;
this.time.addEvent({ callback: () => { label.text += text[i]; ++i; }, repeat: length - 1, delay: delay });}2. 使い方 (Usage)
Section titled “2. 使い方 (Usage)”create メソッドなどで、作成した関数を呼び出します。
create() { // 1. 空のテキストオブジェクトを作成 const label = this.add.text(50, 100, '', { fontSize: '32px', color: '#ffffff', wordWrap: { width: 700 } });
// 2. 表示したいテキスト const content = "Hello, Phaser 3!\nThis is a typewriter effect.\nEnjoy coding!";
// 3. タイプライターエフェクトを実行 this.typewriteText(label, content);}完全なソースコード
Section titled “完全なソースコード”クラス全体を見る
import Phaser from 'phaser';
export class TypewriterScene extends Phaser.Scene { constructor() { super('TypewriterScene'); }
create() { const label = this.add.text(50, 100, '', { fontSize: '32px', color: '#ffffff', wordWrap: { width: 700 } });
const content = "Hello, Phaser 3!\nThis is a typewriter effect.\nEnjoy coding!";
this.typewriteText(label, content); }
typewriteText(label: Phaser.GameObjects.Text, text: string, delay: number = 100) { const length = text.length; let i = 0;
this.time.addEvent({ callback: () => { label.text += text[i]; ++i; }, repeat: length - 1, delay: delay }); }}実装のポイント
Section titled “実装のポイント”-
repeat: length - 1:Phaser.Time.TimerEventのrepeatオプションを使用することで、コードをシンプルに保っています。文字数分だけ正確にループが実行されます。 -
汎用的なメソッド:
typewriteTextメソッドはPhaser.GameObjects.Textと文字列を受け取る設計になっているため、他のシーンでも再利用が容易です。