Aframe how to get intersected elements from raycaster-intersection event

Viewed 807

I have a raycaster-intersection event listener attached to my right laser controller like so:

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

...

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

Collidable object example:

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

When the raycaster intersects with a .collidable object the event is successfully emitted but I can't find any information on the intersected object from the event variable (e). I really don't want to have to attach events to each of these objects because I'd have like 20 event listeners.

Console output: enter image description here

It's like the event output is incomplete...Aframe docs imply the 'els' array should contain what I'm looking for but it's empty. There's also no .getIntersection() function. Any ideas?

1 Answers

Using the A-Frame 1.2.0

The event you want to listen to is: raycaster-intersected

then you can get the intersection data from: evt.detail.el.components.raycaster that also has the getIntersection(el) method

Example below.

<!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>

Related