LoginSignup
0
0

More than 5 years have passed since last update.

【Playcanvas】Image Elementのフェード処理【2D】

Posted at

【Playcanvas】Image Elementのフェード処理【2D】

チュートリアル

の「fade.js」では3Dオブジェクトにアタッチしたマテリアルのフェードアウト処理を行っています。
今回はこのスクリプトを改造し2D Screen上で表示する「Image element」のフェードアウト処理を実装します。
(タイトル画面やUIでは「Image element」の方が取り扱いやすいため調査した次第です)

「Image element」では「Texture」「Material」のいづれか一方を指定します。
両方とも対応した形になります。

※「Material」を使う場合はアタッチした「Material」の「OPACITY」の「Blend Type」を「Alpha」にしてください。
この指定がないと透過度が変わらないからです。


var Fade = pc.createScript('fade');

Fade.attributes.add('event', { type:'string' });
Fade.attributes.add('type', {
    type: 'number',
    enum: [
        { 'In': 0 },
        { 'Out': 1 },
        { 'InOut': 2 }
    ]
});
Fade.attributes.add('duration', { type:'number', default: 0.25 });

// initialize code called once per entity
Fade.prototype.initialize = function() {
    var app = this.app;

    this.timer = 0;
    app.on(this.event, function () {
        this.timer = this.duration;
    }, this);

    this.displayType = 'none';
    this.model = null;

    this.model = this.entity.element;

    if (this.entity.element.material.name === 'Untitled') {
        this.displayType = 'texture';
    } else {
        this.displayType = 'material';
    }
};

// update code called every frame
Fade.prototype.update = function(dt) {
    if (this.timer > 0) {
        this.timer = Math.max(this.timer - dt, 0);

        // Normalize
        var x = (this.duration - this.timer) / this.duration;
        var y;

        switch (this.type) {
            case 0:
                y = x;
                break;
            case 1:
                y = 1 - x;
                break;
            case 2:
                y = Math.abs((x / 2 + 0.25) % 0.5 - 0.25) * 4;
                break;
        }

        var enabled = false;

        enabled = this.model.enabled;

        if (enabled && y === 0) {
            this.model.enabled = false;
            y = 1;
        } else if (!enabled && y > 0) {
            this.model.enabled = true;
        }        

        switch (this.displayType) {
            case 'material':
                var material = this.model.material;
                material.opacity = y;
                material.update();                
                break;
            case 'texture':
                this.model.opacity = y;
                break;
            default:
                break;
        }
    }
};

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0