メインコンテンツまでスキップ

UI - プログレスバー

Elementコンポーネントを使用するプログレスバー。フルシーンを参照してください

ビルトインElementsを使用してプログレスバーを簡単に作成できます。本チュートリアルでは、数秒ごとに空からいっぱいにループするプログレスバーを使用しています。

ヒエラルキー (Hierarchy)​

UIの構造は次のようになります。

Hierarchy

スクリーンの設定​

スクリーンは次のように設定されています。

Screen

2Dスクリーンであるため、 Screen Space を選択しました。 Reference Resolution は、ターゲットとしている解像度です。この場合、1080 x 1920です。スケールモードとしてBlendを選択しているため、スクリーンは解像度の変更に適応します。また、スケールブレンドを1に設定しているため、スクリーンは高さの変更にのみ適応されます。

スクリーンには、POWERテキストを表示するための子テキストエレメントと、プログレスバーを表示するためのエンティティであるProgress Barが含まれています。

プログレスバーの設定​

プログレスバーは2つのElementで構成されています。バックグラウンド画像とフィル画像です。

バックグラウンド画像はProgress Barエンティティです。それには、プログレスバーの背景画像を表示する画像エレメントがあります。

Background Image

フィル画像は、Fill Imageエンティティです。それはProgress Barエンティティの子要素であり、プログレスバーのフィルを表示するImage Elementがあります。このイメージは、親バックグラウンド画像の左にアンカーが設定されているため、要素の幅を変更してプログレスバーを拡大できます。

Fill Image

スクリプト (Script)​

Progress Barエンティティには、プログレスバーのサイズ変更を制御するスクリプトが用意されています。

import { Entity, Script, math } from 'playcanvas';

/**
* A simple progress bar component that adjusts a fill image's width based on a 0-1 progress value.
*/
export class ProgressBar extends Script {
static scriptName = 'progressBar';

/**
* The entity that shows the fill image.
*
* @attribute
* @title Progress Image
* @type {Entity}
*/
progressImage;

/**
* The maximum width of the fill image.
*
* @attribute
* @title Progress Image Max Width
* @type {number}
*/
progressImageMaxWidth;

initialize() {
// Use our own rect object to set the size of the progress bar
this.imageRect = this.progressImage.element.rect.clone();

// Initialize progress to 0
this.setProgress(0);

// If true, the progress bar will increase; otherwise, it will decrease in update
this.increase = true;
}

/**
* Set progress - value should be between 0 and 1.
* @param {number} value
*/
setProgress(value) {
// Clamp value between 0 and 1
value = math.clamp(value, 0, 1);

this.progress = value;

// Calculate desired width of the fill image
const width = math.lerp(0, this.progressImageMaxWidth, value);
this.progressImage.element.width = width;

// Update the rect to reflect progress
this.imageRect.copy(this.progressImage.element.rect);
this.imageRect.z = value;
this.progressImage.element.rect = this.imageRect;
}

/**
* Automatically increase or decrease the progress each frame.
* @param {number} dt - Delta time since the last frame.
*/
update(dt) {
const diff = this.increase ? dt : -dt;
this.setProgress(this.progress + diff);

if (this.progress >= 1) {
this.increase = false;
} else if (this.progress <= 0) {
this.increase = true;
}
}
}

このスクリプトには、フィル画像を表示するエンティティとその画像の最大幅という2つの属性があります。関数setProgressは0から1までの値でプログレスを設定します。

updateメソッドでは、進行状況を0から1の間でループさせます。このスクリプトで重要な点は、進行バーを適切にリサイズするために、widthとrectを変更する必要があることです。

widthを変更すると、フィルイメージが大きくなります。また、rectを変更することで、表示されるテクスチャの部分のみを表示し、表示されるテクスチャを伸ばさないようにします。こちらはrectのAPIリファレンスです。