首页 > 解决方案 > Aframe 如何从 raycaster-intersection 事件中获取相交元素

问题描述

我有一个 raycaster-intersection 事件侦听器连接到我的右侧激光控制器,如下所示:

<a-entity id="rightController" laser-controls="hand: right" raycaster="objects: .collidable; far: 20"></a-entity>

...

rightController.addEventListener("raycaster-intersection", function(e) {
   console.log(e);
});

可碰撞对象示例:

<a-sphere class="collidable" color="yellow" radius="5" position="31.617 7.159 -10.258" scale="0.1 0.1 0.1"></a-sphere>

当 raycaster 与 .collidable 对象相交时,事件成功发出,但我无法从事件变量 (e) 中找到有关相交对象的任何信息。我真的不想将事件附加到这些对象中的每一个,因为我需要 20 个事件侦听器。

控制台输出: 在此处输入图像描述

就像事件输出不完整...... Aframe 文档暗示“els”数组应该包含我正在寻找的内容,但它是空的。也没有 .getIntersection() 函数。有任何想法吗?

标签: three.jsaframeraycasting

解决方案


使用 A-Frame 1.2.0

你要监听的事件是:raycaster-intersected

然后您可以从以下位置获取相交数据:evt.detail.el.components.raycaster也具有getIntersection(el)方法

下面的例子。

<!DOCTYPE HTML>

<head>
  <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
</head>

<body>
  <script>
  AFRAME.registerComponent('cursor-listener', {
    init: function () {
      this.el.addEventListener('raycaster-intersected', evt => {
        this.raycaster = evt.detail.el;
      });
      this.el.addEventListener('raycaster-intersected-cleared', evt => {
        this.raycaster = null;
      });
    },
    tick: function () {
        if (!this.raycaster) { return; }  // Not intersecting.
        let intersection = this.raycaster.components.raycaster.getIntersection(this.el);
        if (!intersection) { return; } // Not intersecting
        // intersecting
        console.log(intersection);
    }
  });
  </script>
  <a-scene id="scene">
    <a-entity cursor="rayOrigin: mouse" raycaster="objects: .cursor-listener"></a-entity>
    
    <a-plane
        position="0 1.6 -1"
        height="2"
        width="1.5"
        color="red"
        class="cursor-listener"
        cursor-listener
        id="element"
      ></a-plane>
  </a-scene>
</body>


推荐阅读