コンテンツにスキップ

Count Up (数値カウント)

スコア獲得時やダメージ表示、リザルト画面などでよく使われる、数値がガーッと増えていく演出です。 Phaser.Tweens を使って変数の値を変化させ、その値を onUpdate コールバックでテキストに反映させることで実現します。

シーンクラスに追加するヘルパーメソッドです。

/**
* 数値をカウントアップさせる
* @param target 表示対象のテキストオブジェクト
* @param start 開始値
* @param end 終了値
* @param duration 期間(ms)
* @param ease イージング (デフォルト: 'Cubic.out')
*/
public countUp(target: Phaser.GameObjects.Text, start: number, end: number, duration: number, ease: string = 'Cubic.out') {
// 数値を保持するダミーオブジェクト
const tweenObject = { value: start };
this.tweens.add({
targets: tweenObject,
value: end,
duration: duration,
ease: ease,
onUpdate: () => {
// 現在の値を整数にしてテキストに反映
target.setText(Math.floor(tweenObject.value).toLocaleString());
},
onComplete: () => {
// 念のため最終値をセット
target.setText(end.toLocaleString());
}
});
}
create() {
const label = this.add.text(400, 200, '0', { fontSize: '80px' });
// 0 から 10000 まで 2秒かけてカウントアップ
this.countUp(label, 0, 10000, 2000);
}
クラス全体を見る
import Phaser from 'phaser';
export class CountUpScene extends Phaser.Scene {
constructor() {
super({ key: 'CountUpScene' });
}
create() {
this.add.text(10, 10, 'Count Up Demo', {
fontFamily: '"Noto Sans JP", sans-serif',
fontSize: '24px',
color: '#00ff00'
});
// 1. 表示用のテキストオブジェクト
const label = this.add.text(400, 200, '0', {
fontFamily: '"Noto Sans JP", sans-serif',
fontSize: '80px',
color: '#ffffff',
fontStyle: 'bold'
}).setOrigin(0.5);
// 2. カウントアップを実行 (0 -> 10000)
// デモ用に繰り返す
const startDemo = () => {
label.setText('0');
this.countUp(label, 0, 10000, 2000);
this.time.delayedCall(3000, startDemo);
};
startDemo();
}
/**
* 数値をカウントアップさせる
* @param target 表示対象のテキストオブジェクト
* @param start 開始値
* @param end 終了値
* @param duration 期間(ms)
* @param ease イージング (デフォルト: 'Cubic.out')
*/
public countUp(target: Phaser.GameObjects.Text, start: number, end: number, duration: number, ease: string = 'Cubic.out') {
const tweenObject = { value: start };
this.tweens.add({
targets: tweenObject,
value: end,
duration: duration,
ease: ease,
onUpdate: () => {
target.setText(Math.floor(tweenObject.value).toLocaleString());
},
onComplete: () => {
target.setText(end.toLocaleString());
}
});
}
}
  1. ダミーオブジェクトのTween: 直接テキストオブジェクトの数値をTweenすることはできません(文字列なので)。{ value: start } という単純なオブジェクトを作り、その value プロパティをTweenさせます。

  2. onUpdate: Tweenのフレームごとに呼ばれる onUpdate 内で、現在の value を取得し、setText で画面に反映します。ここで Math.floor することで整数表示にします。