Skip to content

Instantly share code, notes, and snippets.

@Strae
Last active April 22, 2020 09:23
Show Gist options
  • Save Strae/8b62ee637699b4218b53b3f158351864 to your computer and use it in GitHub Desktop.
Save Strae/8b62ee637699b4218b53b3f158351864 to your computer and use it in GitHub Desktop.
Aframe opacity on 3D objects

@source: https://stackoverflow.com/questions/43914818/alpha-animation-in-aframe-for-a-object-model

The built-in material component primarily works with primitives, so material="opacity: 0.5" and similarly opacity="0.5" will not work here. You'll need to modify the THREE.js materials created by your model, using a custom component. Example:

AFRAME.registerComponent('model-opacity', {
  schema: {default: 1.0},
  init: function () {
    this.el.addEventListener('model-loaded', this.update.bind(this));
  },
  update: function () {
    var mesh = this.el.getObject3D('mesh');
    var data = this.data;
    if (!mesh) { return; }
    mesh.traverse(function (node) {
      if (node.isMesh) {
        node.material.opacity = data;
        node.material.transparent = data < 1.0;
        node.material.needsUpdate = true;
      }
    });
  }
});

You can then use, and animate, the component like this:

<a-entity obj-model="obj: model.obj; mtl: model.mtl;" model-opacity="1">
  <a-animation attribute="model-opacity"
               dur="10000"
               from="1"
               to="0"
               repeat="indefinite"></a-animation>
</a-entity>

For more on how this works, see the docs on THREE.Material and writing a component.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment