Search code examples
aframear.js

Wrong position of a clickable object on AR.js scene


I have a simple AR.js scene that should display a clickable white box on a hiro marker. After click the box's colour should change to red. In fact, the box is clickable and the colour is changing, but it's position and the position of it's clickable area are not the same. In my case this area is beneath the box. Here's a code example:

<!DOCTYPE html>
<html>
  <script src="https://aframe.io/releases/0.9.2/aframe.min.js"></script>
  <script src="https://rawgit.com/jeromeetienne/ar.js/master/aframe/build/aframe-ar.js"></script>
  <script>
    AFRAME.registerComponent('clickhandler', {
      init: function () {
        this.el.addEventListener('click', () => {
          this.el.setAttribute('material', 'color: red;');
        });
      },
    });
  </script>
  <body>
    <a-scene embedded arjs>
      <a-marker cursor="rayOrigin: mouse;" preset="hiro">
        <a-box
          material="color: white;"
          position="0 0 0"
          depth="0.2"
          height="0.01"
          width="0.2"
          clickhandler
        />
      </a-marker>
      <a-entity camera></a-entity>
    </a-scene>
  </body>
</html>

However, if you open the aframe inspector (Ctrl + Alt + I) and then close it, box's clickable area and it's position will be correct and I don't understand how is that happening. So how can I make this scene to display the right way?


Solution

  • I've explored how the aframe inspector works and found that it inserts a new raycaster programmatically after it's initialization, so I've decided to do the same and it worked!

    All you need to do to place clickable area in the same spot with it's object is to execute these lines after the scene is fully initialized.

    const scene = AFRAME.scenes[0];
    if (!scene) {
      return;
    }
    const mouseCursor = document.createElement('a-entity');
    mouseCursor.setAttribute('cursor', 'rayOrigin', 'mouse');
    scene.appendChild(mouseCursor);