4

image

in the above image ineed the angle between the two points

if green dot is considered as origin (px,py) ie (0,0) and red dot is (ax,ay)

by the way in the above image angle should be around 45 degree.... acute angle

more ex:

3:00 is 0 degree 12:00 is 90 degree 9:00 is 180 degree 6:00 is 270 degree

here's the code i have tried so far:

function angle(cx, cy, ex, ey) { var dy = ey - cy; var dx = ex - cx; var theta = Math.atan2(dy, dx); // range (-PI, PI] theta *= 180 / Math.PI; // rads to degs, range (-180, 180] if (theta < 0) theta = 360 + theta; // range [0, 360) return theta; } 
5
  • 1
    What's the question? The code seems to work. Commented Nov 16, 2018 at 12:22
  • the question is this code giving me wrong angles.... the image has an angle around 45 degrees but it is showing some like 200(this value is probably wrong cause i dont remember it perfectly) something... do something so ican get 3 o clock as 0 degrees and 9oclock as 180degreess Commented Nov 16, 2018 at 12:25
  • 2
    Your function gives 0° at 3:00, 90° at 12:00, 180° at 9:00 and 270° at 6:00. As far as I can tell, this is exactly what you asked for. So again, what’s the question here? Commented Nov 16, 2018 at 12:36
  • Please tell us what exact call You make, what is the expected result and what is the actual result. Commented Nov 16, 2018 at 12:52
  • 1
    BTW maybe You just put the points in the call in reverse order, because if A->B is 45 degrees, then B->A is 225 degrees. Commented Nov 16, 2018 at 12:54

2 Answers 2

3

Try this out, Working fine for me.

function angle(cx, cy, ex, ey) { var dy = ey - cy; var dx = ex - cx; var theta = Math.atan2(dy, dx); // range (-PI, PI] theta *= 180 / Math.PI; // rads to degs, range (-180, 180] //if (theta < 0) theta = 360 + theta; // range [0, 360) return theta; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Found so many wrong answers for this. Your solution however, with line 5 uncommented, worked exactly as I expected 👍🏼
0

This should work:

function CalcAngle(px, py, ax, ay) { return Math.atan((ax-px)/(ay-py)); } 

Or if the origin is always 0, 0 then this should work:

function CalcAngle(ax, ay) { return Math.atan(ax/ay); } 

I am not sure if yours works but this one should if you want to try it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.