Search code examples
javascriptmathtrigonometryatan2

Rotating an image to face mouse point using ATAN instead of ATAN2


In order to better understand how trigonometry works in game development, I've been creating little javascript snippets on CodePen.

I managed to create an example that uses Math.atan2() to point a pixel-art shotgun at the mouse cursor.

Now, I am trying to accomplish the same exact thing using the Math.atan() function but it isn't functioning properly.

Here is the logic code I am using:

canvas.onmousemove = function(event) {
  Mouse = {
    x: event.pageX,
    y: event.pageY
  }

  // These length variables use the distance formula
  var opposite_length = Math.sqrt((Mouse.x - Mouse.x) * (Mouse.x - Mouse.x) + (Mouse.y - y) * (Mouse.y - y));

  var adj_length = Math.sqrt((Mouse.x - x) * (Mouse.x - x) + (y - y) * (y - y));


  var angle_in_radians = Math.atan(opposite_length / adj_length);

  //var angle_in_radians = Math.atan2(Mouse.y - y, Mouse.x - x);

  angle = angle_in_radians * (180 / Math.PI);
}

The in my draw() function, I rotate the gun to the angle var using:

cxt.rotate(angle*(Math.PI/180));

If you uncomment the line that starts as // var angle_in_radians, everything will suddenly work.

So, atan2 is working, but atan is producing the result I want.

I know that opposite_length and adj_length are accurate, because when i console.log() them, they are the correct values.

You can check out the code being used on CodePen for a live example.

There's a lot of initialization stuff but you only really need to focus on the canvas.onmousemove = function(event) section, starting on line 50. You can also check out my draw function on line 68.


Solution

  • Note that your atan computation is equivalent to

    atan2( abs(mouse.y-y), abs(mouse.x-x) )
    

    The screen coordinates have the opposite orientation to the cartesian coordinates. To get a cartesian angle from screen coordinates, use

    atan2( y-mouse.y, mouse.x-x )