Search code examples
javascriptthree.jsaframe

Making a Button to move an object


I am making an A-Frame site and I need to create a button to move a ball with the id:"test" to it's starting position: 0 8 0. I've tried with the setAttribute script and it doesn't work. This is the javascript code I'm currently working with:

AFRAME.registerComponent('ballreset', {
  events: {
    click: function(evt)
    {
      document.getElementById('test').setAttribute('position', {x:0, y:8, z:0});
      
    }
  }
});

Edit: I found a typo in the code. But didn't solve problem


Solution

  • Without a full example its hard to tell what exactly is the problem but,

    • make sure you do have a raycaster - based cursor component. Mouse clicks won't work with webGL renders like they do with HTML elements.
    • make sure the click listener is working, ie. by logging each click
    • make sure the element with the given id exists at the time of the click

    Below is a working version of something similar to what you want to achieve (click any object):

    <script src="https://aframe.io/releases/1.1.0/aframe.min.js"></script>
    <script>
      AFRAME.registerComponent('foo', {
        events: {
          click: function(evt) {
            // grab the current position
            let pos = this.el.getAttribute("position");
            // move upwards
            this.el.setAttribute('position', { x: pos.x, y: pos.y + 0.25, z: pos.z });
          }
        }
      });
    </script>
    <!-- attach a cursor component -->
    <a-scene cursor="rayOrigin: mouse">
      <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9" foo></a-box>
      <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E" foo></a-sphere>
      <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D" foo></a-cylinder>
      <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4" foo></a-plane>
      <a-sky color="#ECECEC"></a-sky>
    </a-scene>