如何使在联网的 A-Frame 中动态生成的实体可点击?

How to make a entity clickable which is getting generated dynamically in networked A-Frame?

我正在使用联网的 A 框架在页面加载时生成新实体。我想在这些实体上添加一些功能,例如悬停、点击等。我尝试使其可点击,但没有成功。

function rigClick(){
        console.log("Entity Clicked");
      }
<a-scene>
    <a-entity id="rig" onclick="rigClick()">
        <a-entity
          id="foo"
          networked="template:#rig-template;attachTemplateToLocal:false;"
          camera="active:true;"
          position="-27 2.5 24"
          wasd-controls="acceleration:12;"
          look-controls
          spawn-in-circle="radius:2"
        >
        </a-entity>
     </a-entity>
</a-scene>

我也尝试过使用注册组件,但我无法获得结果。

AFRAME.registerComponent('click-handler', {
      init: function () {
        let entity = document.querySelector('#rig')

        entity.addEventListener('click', (e) => {
          console.log("You just clicked on entity");
        })
      }
    });
<a-scene>
    <a-entity id="rig">
        <a-entity
          id="foo"
          networked="template:#rig-template;attachTemplateToLocal:false;"
          camera="active:true;"
          position="-27 2.5 24"
          wasd-controls="acceleration:12;"
          look-controls
          spawn-in-circle="radius:2"
          click-handler
        >
        </a-entity>
     </a-entity>

如果您想使用鼠标,您需要一个 cursor,它将 2D 鼠标点击映射到 3D 射线,检查鼠标光标下的内容:

<script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
<script>
// declare a component
AFRAME.registerComponent("click-detector", {
 // called upon initialisation
 init: function() {
   // when a click is detected
   this.el.addEventListener("click", () => {
    // log "clicked"
    console.log("clicked")
   })
 }
})
</script>
<a-scene cursor="rayOrigin: mouse" raycaster="objects: a-sphere">
  <a-sphere position="0 1.25 -2" radius="1.25" color="#EF2D5E" click-detector></a-sphere>
</a-scene>

aframe-networked 中工作相同,只要您将组件添加到 networked-template,以便每个新的 'player' 都附加组件:

<template id="avatar-template">
  <a-entity class="avatar">
    <a-sphere class="head" scale="0.45 0.5 0.4" click-detector></a-sphere>
  </a-entity>
</template>