FutureCake
FutureCake

Reputation: 2943

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.

Upvotes: 3

Views: 2823

Answers (2)

Danny Yaroslavski
Danny Yaroslavski

Reputation: 512

This is easiest to compute if you make a chart of the values you have and what you expect instead.

Have -> Want

-180 -> 270

-90 -> 0

0 -> 90

90 -> 180

180 -> 270

We see that this can be split into two cases:

[-180, -90)

and

[-90, 180]

Case 1

[-180, -90) -> [270, 360)

The rule is simply +450

Case 2

[-90, 180] -> [0, 270]

This one is just +90

So we get our code

sanitize(angle){ // expecting angle within [-180, 180]
    if(angle < -90){
        return angle + 450;
    } else {
        return angle + 90;
    }
}

Upvotes: 1

le_m
le_m

Reputation: 20228

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>

Upvotes: 5

Related Questions