Black
Black

Reputation: 20212

Determine angle between 3 coordinates

As you can see in my screenshot i try to calculate the angle between the coordinates AB and BC, in this case the angle is obviously 90°. But how can i determine this angle with javascript code?

I try to determine the angle between AB and BC

I found this thread and tried the accepted solution, but i always get 1.57instead of 90 like i expected. I rewrote the original function because i did not understood how to pass my parameters to it.

Please excuse my bad paint and math skills.

	function find_angle(Ax,Ay,Bx,By,Cx,Cy)
	{
		var AB = Math.sqrt(Math.pow(Bx-Ax,2)	+	Math.pow(By-Ay,2));    
		var BC = Math.sqrt(Math.pow(Bx-Cx,2)	+ 	Math.pow(By-Cy,2)); 
		var AC = Math.sqrt(Math.pow(Cx-Ax,2)	+ 	Math.pow(Cy-Ay,2));
		
		return Math.acos((BC*BC+AB*AB-AC*AC)	/	(2*BC*AB));
	}
	var angle = find_angle
				(
					4 ,		//Ax
					3 ,		//Ay
					
					4 ,		//Bx
					2 ,		//By
					
					0 ,		//Cx
					2		//Cy
				)
				
	alert ( angle );

Upvotes: 2

Views: 2103

Answers (2)

newzad
newzad

Reputation: 706

The answer is given in radians in that thread.

1.57 radians is 90 degrees (pi/2). You can convert the answer to degrees by multiplying it with 180/pi.

A = { x: 4, y: 3 };
B = { x: 4, y: 2 };
C = { x: 0, y: 2 };

alert(find_angle(A,B,C));

function find_angle(A,B,C) {
    var AB = Math.sqrt(Math.pow(B.x-A.x,2)+ Math.pow(B.y-A.y,2));    
    var BC = Math.sqrt(Math.pow(B.x-C.x,2)+ Math.pow(B.y-C.y,2)); 
    var AC = Math.sqrt(Math.pow(C.x-A.x,2)+ Math.pow(C.y-A.y,2));
    
    return Math.acos((BC*BC+AB*AB-AC*AC) / (2*BC*AB)) * (180 / Math.PI);   
}

Upvotes: 8

Lutz Lehmann
Lutz Lehmann

Reputation: 25972

Set v = A - B and w = C - B. Then the angle between v and w is the angle between vx+i*vy and wx+i*wy is the argument of w/v (as complex numbers) which is up to positive factors

(wx+i*wy)*(vx-i*vy)=wx*vx+wy*vy+i*(wy*vx-wx*vy).

The argument of a complex number is best computed using the atan2 function, thus

angle = atan2( wy*vx-wx*vy , wx*vx+wy*vy)

As previously said, the angles used are in radians, so you have to convert to degrees if desired.

Upvotes: 3

Related Questions