Search code examples
javascriptjqueryaframewebvr

Creating a compass in aframe


I am trying to create the compass inside the A-Frame scene based on mouse click and drag... but the problem I am facing here is based on mouse cursor movement; the image get rotated.

function diff(x, y) {
  var centerItem = $('#pointer'),
      centerLoc = centerItem.offset();
  var dx = x - (centerLoc.left + (centerItem.width() / 2));
  dy = y - (centerLoc.top + (centerItem.height() / 2));
  return Math.atan2(dy, dx) * (180 / Math.PI);
}

$('body').mousemove(function(e) {
  var x = e.pageX;
  var y = e.pageY;
  var myAngle = diff(x, y);
  var rotationValue = 'rotate(' + myAngle + 'deg)';

  $("#pointer").css({
    '-moz-transform': rotationValue, // FireFox
    '-webkit-transform': rotationValue, // Chrome
    '-o-transform': rotationValue,
    '-ms-transform': rotationValue,
    'transform': rotationValue
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<img class="compass" src="http://i.imgur.com/YahETIk.png" id="pointer" />

How can I solve this? Thanks in advance.


Solution

  • Rather than the mousemove, use the camera rotation.

        <script>
        AFRAME.registerComponent('compass', {
          init: function () {
            this.pointer = document.getElementById('pointer');
          },
    
          tick: function () {
            var yRotation = this.el.getAttribute('rotation').y;
            this.pointer.style.transform = 'rotate(' + yRotation + 'deg)';
          }
        });
        </script>
    
        <img class="compass" src="http://i.imgur.com/YahETIk.png" id="pointer"/>
    
        <a-scene>
          <a-camera compass></a-camera>
        </a-scene>