Deep Fade - Fade In/Out an entity and all of its children

I made the following code to make it easy to fade in or fade out an entity and all of its children(and grand children, etc. It doesn’t stop at the first level if there’s more). By fading out/fadin in an entity I mean texts, images, and models.

I think this is super useful when you want to switch screens with a nice fade effect, etc. If you can improve it to include other things that are not currently fadeable let me know.

Just attach it to the parent entity, and call fadeIn(seconds, onComplete) or fadeOut(seconds, onComplete).

var DeepFade = pc.createScript('deepFade');

// initialize code called once per entity

DeepFade.prototype.initialize = function() {

    this.fadeOutFrom = {value: 1};

    this.fadeInFrom = {value: 0};

    this.materials = this.entity.findComponents('render').map(render => render.meshInstances).flat().map(meshInstance => meshInstance.material);

    this.imagesTexts = this.entity.findComponents("element").filter(e => e._type === pc.ELEMENTTYPE_TEXT || e._type === pc.ELEMENTTYPE_IMAGE);

};

DeepFade.prototype.fadeOut = function(seconds, onComplete) {

    this.app.tween(this.fadeOutFrom).to({value: 0}, seconds, pc.SineOut)

    .on('update', function() {

        this.imagesTexts.forEach(imageText => imageText.opacity = this.fadeOutFrom.value);

        this.materials.forEach(material => {

            material.opacity = this.fadeOutFrom.value;

            material.update();

        });

     }

     .bind(this))

     .on('complete', function() { onComplete && onComplete(); }.bind(this))

     .start();

};

DeepFade.prototype.fadeIn = function(seconds, onComplete) {

    this.app.tween(this.fadeInFrom).to({value: 1}, seconds, pc.SineOut)

    .on('update', function() {

        this.imagesTexts.forEach(imageText => imageText.opacity = this.fadeInFrom.value);

        this.materials.forEach(material => {

            material.opacity = this.fadeInFrom.value;

            material.update();

        });

    }.bind(this))

    .on('complete', function() { onComplete && onComplete(); }.bind(this))

    .start();

};
2 Likes

Wow, this is great @Marks! Will definitely be saving and using this for our games in the future! On mobile, so I wasn’t able to read the code properly, but does this work for the legacy model component too?

1 Like

It should work, yes. Let me know if it doesn’t!

1 Like