import * as Phaser from 'phaser';
export class ScoreText extends Phaser.GameObjects.Text {
constructor(scene: Phaser.Scene, x: number, y: number) {
// 初期化時にレジストリから 'score' の値を取得(なければ0)
const currentScore = scene.registry.get('score') || 0;
super(scene, x, y, `Score: ${currentScore}`, {
fontSize: '32px',
color: '#ffffff'
});
// シーンにこのテキストオブジェクトを追加
scene.add.existing(this);
// registryの'score'データが変更されたら表示を更新するイベントを登録
scene.registry.events.on('changedata-score', this.updateScore, this);
// シーンが破棄・シャットダウンされる時にイベントを解除(メモリリーク防止)
scene.events.on('shutdown', () => {
scene.registry.events.off('changedata-score', this.updateScore, this);
});
}
private updateScore(parent: any, value: number): void {
this.setText(`Score: ${value}`);
}
// スコアを加算するための便利なメソッド
public addScore(amount: number): void {
const currentScore = this.scene.registry.get('score') || 0;
this.scene.registry.set('score', currentScore + amount);
}
}