Rotating object to face mouse pointer on mousemove

32,126

Solution 1

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

Solution 2

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');
  });
});
Share:
32,126

Related videos on Youtube

CaptainCarl
Author by

CaptainCarl

Updated on August 03, 2022

Comments

  • CaptainCarl
    CaptainCarl over 1 year

    I've got a mousemove cursor in my game which will make my object shoot towards my mouse cursor. I'd like my object to always rotate along to be in line with my mousecursor. How can i convert the X and Y of where the cursor is to a degree angle to rotate my object to?

    I hope my fiddle will make things a little clearer of to what i mean by rotating the player(Black block): http://jsfiddle.net/3nEUv/4/

    Here's my mouseMove function now; Only making sure the cursor remains in it's bounding box

    function mouseMove(e) {
        if (cursor) {
            if (e.rawX && e.rawY) {
                cursorBoundingBox(e.rawX, e.rawY);
            }
        }
    }
    
  • CaptainCarl
    CaptainCarl about 11 years
    Easy games are for suckers!! :-p I'm gonna check it out. Could you perhaps specify some of the things you're doing in the code? I'm not really a math genius so :D
  • OpherV
    OpherV about 11 years
    Sure, I'll include some graphic illustrating the calculation. It's really simple geometry :)
  • CaptainCarl
    CaptainCarl about 11 years
    I guess i'm doing something wrong, but this isn't the way it rotated in your example; What am i doing wrong? jsfiddle.net/6TqjC (Mousemove is on 498)
  • OpherV
    OpherV about 11 years
    I've updated my answer, see if that helps clear up things. If not, please let me know and I'll have a look a bit later!
  • CaptainCarl
    CaptainCarl about 11 years
    I think i somewhat get it. Nonetheless i can't get it to work properly. I might have the wrong data from my mouse event or something..? See my comment 46 minutes ago.
  • futurecat
    futurecat about 11 years
    @CaptainCarl Your box center calculation is incorrect. Change the pos/size to a pos-size, i.e. [player.sprite.x/(player.sprite.width/2), player.sprite.y/(player.sprite.height/2)]; to [player.sprite.x-(player.sprite.width/2), player.sprite.y-(player.sprite.height/2)];
  • CaptainCarl
    CaptainCarl about 11 years
    That's just a dumb mistake. Thanks alot @Deestan
  • OpherV
    OpherV about 11 years
    @Deestan you beat me to the punch :D Glad it worked out for you Carl
  • Fabio Delarias
    Fabio Delarias about 7 years
    I would just like to point out for anybody coming to this post like I did. that Math.atan2() takes Y as the first number and X as the second number. Here is the link developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • Mayur Kukadiya
    Mayur Kukadiya about 4 years
    I Have tried this code in my project and working fine, But I need to get the value of a degree from 0-360, but I can't get it from the above formula. can you please help?
  • Dror Bar
    Dror Bar over 3 years
    I need angle to be between 0 and 360, not -180 and 180. Is there a better way to do it other than angle = parseInt(angle < 0 ? 360 + angle : angle ); ? For example in the Math.atan2 formula?
  • OpherV
    OpherV over 3 years
    @DrorBar if you add 180 to the -180 to 180 range you get 0 to 360 range ...