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();
};