Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate angle between 2 vectors return value in degrees between 0 and 360

Hey I have the following code that calculates the angle in degrees:

var angleDeg = Math.atan2(mouse.y - base.y, mouse.x - base.x) * 180 / Math.PI;
console.log(angleDeg);

but at the moment i get the angle between 0 and 180 degrees positive and negative. with 0 deg at the right see image. But i want the returned angles to be between 0 and 360 all positive. with the 0 deg at the top. see image.

enter image description here

How do i update my function so this works? I write this in javascript. So in the end i want the angle values to be returned as the pink in the image. Any help is greatly appreciated!!!

hopefully this is clear if not pls let me know so i can update my question.

like image 830
FutureCake Avatar asked Nov 30 '25 12:11

FutureCake


1 Answers

You need to "rotate" your mouse.x and mouse.y coordinates about 90° (=swap y, x with -x, y) and add an offset of 180° (= Math.PI):

let base = {x: 100, y: 100};

document.addEventListener('mousemove', event => {
  let angle = Math.PI + Math.atan2(-event.x + base.x, event.y - base.y);
  console.log(angle * 180 / Math.PI);
});
<div style="position: absolute; top: 100px; left: 100px">x</div>
like image 129
le_m Avatar answered Dec 03 '25 01:12

le_m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!