- Home /
Angle between two lines in 2D
Hey, I've got a problem dealing with the Vector2.Angle and the Vector3.Angle The thing is during runtime I define three points A,B and C which are in 2D world.
and eventually two lines will be used , (A,B) and (B,C) I'm trying to figure out the angle between those two lines. I've tried Vector2.Angle(B-A,C-B) and bunch of others, but I think I don't understand the essential concept of the Angle() method.
The picture will illustrate my point! Click Here
how to calculate Alpha ??
Thanks for your time
Answer by rutter · Jun 24, 2014 at 07:04 PM
So you're describing a shape like this?
It's important to note that vectors have both length and direction. The vector from A to B is not the same as the vector from B to A. They have equal length, but opposite direction.
So, this bit:
Vector2.Angle(B-A,C-B)
That's not running the comparison you might expect, because one of your vectors is pointing "backwards". You end up calculating the supplementary angle:
So, what you probably want is this:
Vector2.Angle(B-A, B-C);
Awesome man.... Thanks a lot, it did the trick
Have a good one !
Answer by Zoodinger · Jun 24, 2014 at 01:24 PM
The dot product between two vectors returns the cosine of the angle.
float dot = Vector2.Dot(A, B);
float angleInRadians = Mathf.Acos(dot);
float angle = Mathf.Rad2Deg(angleInRadians); //to degrees
Note: A and B need to be NORMALIZED for this to work!
Keep in mind that this will only produce angles between 0 and 180 degrees. You'll need to do some additional trickery to compensate for that. For 2d vectors this is not too hard:
Vector3 cross = Vector3.Cross(new Vector3(A.x, A.y, 0), new Vector3(B.x, B.y, 0));
cross.z will be positive if the rotation is clockwise or negative if the rotation is counter-clockwise. Or the other way around, I'm not sure :P. Either way, you'll be able to figure out what to do in case you want to detect angles larger than 180 degrees.
Answer by Ankit Priyarup · Jun 24, 2014 at 03:14 PM
It's very simple with physics. Let two lines be vector a and vector b then the angle cos theta will equal to A.B(dot product)/a mode cross product to b mode.
The problem is I can't seem to struct the lines A line from A to B is for example : Vector2 AB = A+B; or Vector2 AB = A-B or something else ?!
I mean logically I know it and mathematically but to apply it in unity that's where's my pickle