Rotating object to face mouse pointer on mousemove

Basically you need to find the vector between the the point in the center of your box, and the point of the mouse cursor, then calculate the angle and convert it to degrees. Then just apply the angle via CSS:

let box = document.querySelector(".box");
let boxBoundingRect = box.getBoundingClientRect();
let boxCenter= {
    x: boxBoundingRect.left + boxBoundingRect.width/2, 
    y: boxBoundingRect.top + boxBoundingRect.height/2
};

document.addEventListener("mousemove", e => {
    let angle = Math.atan2(e.pageX - boxCenter.x, - (e.pageY - boxCenter.y) )*(180 / Math.PI);      
    box.style.transform = `rotate(${angle}deg)`;  
})

WAIT, WHAT?

Ok, let's take this apart. This is what we have:

enter image description here

The vector AB goes between the center of the box and the mouse position. We went to calculate Θ (theta), which is the angle between the X axis and AB.

Imagine a line going down from B parallel to the Y axis until it touches the X axis. Using that line, AB and the X axis we get a triangle. That means we can use the Arctan function to calculate theta. More precisely, we use the convenience function of Arctan2 which gives a positive angle when y>0 and negative angle when y<0.

atan2 returns the degrees in radians, and CSS works with degrees, so we convert between the two using 180/Math.PI. (A radian is the measure of an angle that, when drawn a central angle of a circle, intercepts an arc whose length is equal to the length of the radius of the circle. - Taken from here )

One last caveat - Since in the browser the Y axis is inverted (meaning, the further down you go in the page, the higher the Y value gets), we had to flip the Y axis: We did so by adding a minus sign on the Y term:

- (e.pageY - boxCenter[1])

I hope this helps clear some things...

Here's an isolated jsfiddle example

BTW, Your game is hard! :)


I have create a rotation script for the every html element with passing angle of rotation.

Hope it will help

function MouseRotate(e, elt) {
  var offset = elt.offset();
  var center_x = (offset.left) + (elt.width() / 2);
  var center_y = (offset.top) + (elt.height() / 2);
  var mouse_x = e.pageX;
  var mouse_y = e.pageY;
  var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
  var degree = (radians * (180 / Math.PI) * -1) + 90;
  $(elt).css('-moz-transform', 'rotate(' + degree + 'deg)');
  $(elt).css('-webkit-transform', 'rotate(' + degree + 'deg)');
  $(elt).css('-o-transform', 'rotate(' + degree + 'deg)');
  $(elt).css('-ms-transform', 'rotate(' + degree + 'deg)');
}

$(document).ready(function() {
  $('#'+tagVal).mousedown(function(e) {
    $(document).bind('mousemove', function(e2) {
      rotateOnMouse(e2,$('#'+tagVal));
    });
  });
  $(document).mouseup(function(e) {
    $(document).unbind('mousemove');
  });
});