A-Frame + AR.js:如何在点击屏幕时在 Arjs 中动态添加对象?

A-Frame + AR.js: How to add objects dynamically in Arjs when tapping on screen?

我目前正在使用 ar.js 开发 A-Frame AR 应用程序(我必须使用 ar.js)。目标是在点击场景时动态地将对象添加到场景中。不幸的是,似乎没有任何结果。我在屏幕上点击时设法更改了现有对象的颜色,但没有添加新对象。有人可以帮我吗?我将不胜感激!

AFRAME.registerComponent('cursor-listener', {
  init: function () {
  var currentEl = this.el;
  currentEl.addEventListener("click", function (evt) {
  console.log("I was clicked!");
  currentEl.setAttribute('material', {"color": "blue"});
  var el = document.createElement("a-entity");
  el.setAttribute('geometry', { "primitive": "sphere", "radius": "1" });
 
  
  
  el.setAttribute('position', this.el.object3D.position)
  const randomYRotation = Math.random() * 360
  el.setAttribute('rotation', `0 ${randomYRotation} 0`)
  el.setAttribute('visible', 'true')
  el.setAttribute('shadow', {receive: false})
  this.el.sceneEl.appendChild(el);
  });
  },
  });
  

this.el.sceneEl.appendChild(el);

您应该将该元素附加到标记节点,并将其视为您的“根”元素 - 因为它是被相机检测到的被跟踪的元素:

<script>
  AFRAME.registerComponent('cursor-listener', {
     init:function () {
       const marker = document.querySelector("a-marker")
       var el = document.createElement("a-sphere");
       marker.appendChild(el);
     }
  })
</script>
<!-- scene and stuff -->
<a-marker preset="hiro>
</a-marker>