Search code examples
javascripthtmlthree.jsaframewebvr

A-frame check variable with function and show different gltf depending on the value


I am wondering how I can create something like this using JavaScript and A-frame (https://aframe.io).

I would like to create an onload function called load() that will check the value of a variable x and if x is one, the gltf with the id of 1 will show and the gltf's with the id of 2 and 3 will not be visible. The same goes for gltf's 2 and 3. How can I acomplish this? My code:

<script>
var x = 1;

</script>    
<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
<body onload="load()">

  <a-gltf-model  id="1" src="https://cdn.glitch.com/2556b706-79db-4661-ab72-d86cfd5b5649%2Fscene.glb?v=1622850633562" position="-0 6 -1" scale="0.01 0.01 0.01"></a-gltf-model>

  <a-gltf-model  id="2" src="https://cdn.glitch.com/6632f840-a210-4bdc-a62f-bc38e65ae48a%2Fscene%20-%202021-06-12T230318.001.glb?v=1623564342354" position="-0 6 -1" scale="0.01 0.01 0.01"></a-gltf-model>
  <a-gltf-model  id="3"src="https://cdn.glitch.com/6632f840-a210-4bdc-a62f-bc38e65ae48a%2Fwinter.glb?v=1623564477495" position="-0 6 -1" scale="0.01 0.01 0.01"></a-gltf-model>

<a-scene>


</a-scene>
</body>

Solution

  • Store the valid ids in an array and loop through each one, then remove correspondingly.

    const ids = [1, 2, 3];
    
    function load() {
      var x = 1;
      ids.forEach((e) => {
        if (e != x) {
          document.getElementById(e).remove();
        }
      })
    }
    a-gltf-model {
      display: none;
    }
    <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
    
    <body onload="load()">
    
      <a-scene>
    
        <a-gltf-model id="1" src="https://cdn.glitch.com/2556b706-79db-4661-ab72-d86cfd5b5649%2Fscene.glb?v=1622850633562" position="-0 6 -1" scale="0.01 0.01 0.01"></a-gltf-model>
    
        <a-gltf-model id="2" src="https://cdn.glitch.com/6632f840-a210-4bdc-a62f-bc38e65ae48a%2Fscene%20-%202021-06-12T230318.001.glb?v=1623564342354" position="-0 6 -1" scale="0.01 0.01 0.01"></a-gltf-model>
        <a-gltf-model id="3" src="https://cdn.glitch.com/6632f840-a210-4bdc-a62f-bc38e65ae48a%2Fwinter.glb?v=1623564477495" position="-0 6 -1" scale="0.01 0.01 0.01"></a-gltf-model>
        <a-plane width="100" height="100" position=" 0.00 0.00 0.00" rotation="-90 0 0" color="royalblue"></a-plane>
    
    
      </a-scene>
    </body>