Search code examples
aframewebvr

How to show multiple geometry on geometry click in a-frame?


I want to show multiple spheres on a sphere click in a-frame. Suppose I have a sphere and when I will take my cursor to that sphere it will show other spheres and when I click on one of the multiple spheres it will show another multiple spheres.


Solution

  • It depends, if the spheres are predefined, or "procedural".

    If You want to make new spheres on every sphere click, You can make a new component for the scene, listening for any click on any a-sphere, and attaching new spheres to the target:

    AFRAME.registerComponent('foo',{
      init:function(){
         document.querySelector("a-sphere").addEventListener('click',this.createSpheres);
      },
      createSpheres:function(){
        let sphere1 = document.createElement('a-sphere');
        sphere1.setAttribute('position','-1 1 1');
        let sphere2 = document.createElement('a-sphere');
        sphere2.setAttribute('position','2 1 2');
        let sphere3 = document.createElement('a-sphere');
        sphere3.setAttribute('position','-1 -1 -1');
        e.target.appendChild(sphere1);
        e.target.appendChild(sphere2);
        e.target.appendChild(sphere3);
      }
    });
    

    What i do here, is check for the click -> call the function responsible for sphere creation.

    As far as i know, document.querySelector() shouldn't be working, since it should pick the 'first' found selector, but for some reason it works here.

    Live example here: https://jsfiddle.net/wqbxnakr/.


    For predefined objects, just make their first child visible on click:

    AFRAME.registerComponent('bar',{
      init:function(){
        this.el.addEventListener('click',(e)=>{
           this.el.children[0].setAttribute('visible','true');
        }
      }
    });
    

    and attach the component to each chained sphere.