Adding new entities on the fly in AFrame

5.1k Views Asked by At

I'm trying to build an AFrame app where users can click on something and a new scene will show up. From there, the user can click on something else, etc. This scene's data is taken from an API, so it's tough to know all possible scenes the user can encounter.

With this in mind, how would you go about modifying the AFrame scene during runtime? Apparently modifying the DOM doesn't work, but if there is a way to have AFrame re-render the scene at a certain time, that would be awesome. If you think there's another way to approach this, I'd love to hear it. Thanks!

2

There are 2 best solutions below

3
On BEST ANSWER

You can indeed modify DOM during runtime and it will affect the scene. Here is an example of adding a new object using jQuery taken from this project:

function appendObject(id, file, scale, position, rotation, scale) {
        $('<a-obj-model />', {
          id: id,
          class: 'city object children',
          position: position,  // doesn't seem to do anything, known issue
          scale: scale,
          rotation: rotation,
          file: file,
          src: '#' + file + '-obj',
          mtl: '#' + file + '-mtl',
          appendTo : $('#city')
        });
       document.getElementById(id).setAttribute("position", position); // this does set position as a workaround
      }

And here is an example of removing an object:

 onMenuDown: function () {
        previousObject = document.querySelector("#object" + (objectCount - 1));
        previousObject.parentNode.removeChild(previousObject);
        objectCount -= 1;
        if(objectCount == -1) {objectCount = 0};
  },
0
On

Just for future reference since you have already solved your issue, you can use the normal JS DOM API:

var el = document.createElement('a-entity');
document.querySelector('a-scene').appendChild(el);