![]() |
|
Angle Between Two Vectors? |
Mr. Big
Member #6,196
September 2005
|
How do I get the angle between two vectors with the same origin? Thanks. |
Thomas Harte
Member #33
April 2000
![]() |
Are you working out the individual angles of the lines from their origin, then trying to do some arithmetic on those values? If so then that would explain your issues. An easier solution is the dot product. For two vectors, A and B: A . B = |A||B|cos(angle between A and B) |A| is the length of A, so you can find that with Pythagoras. So, if you have A = (ax, ay) and B = (bx, by) then: angle between = acos( ((ax * bx) + (ay * by)) / (sqrt(ax*ax + ay*ay) * sqrt(bx*bx + by*by)) If you use the acos from math.h then the result will be in the range -pi/2 to pi/2. Be careful though — it'll always give you the smallest angle between the vectors, so if two vectors start with the same orientation and then one stays still and the other rotates then the angle between them will go up from 0 to pi/2, then down again from pi/2 to -pi/2, then up from -pi/2 to 0. If you want a full -pi to pi then you need to do a further check to decide if the two vectors are both pointing "the same way". Imagine one vector is lying exactly on the x-axis pointing right. Then you want to decide whether the other is pointing right or left. You can do that using the dot product too — check whether ((ax * bx) + (ay * by)) is negative or positive and add or subtract pi from your result depending on its sign and which angle you want to measure. E.g. (untested, written adhoc)
There's lots on the web about the dot product, and it's something that's very easy to understand the properties of, even if it takes you a while to really see why it all works... [My site] [Tetrominoes] |
Mr. Big
Member #6,196
September 2005
|
Oh! Should have thought about it myself! [EDIT] Your code doesn't actually work because 'atan' returns values in range of 0 - pi, but thanks for the idea with the dot product and angle signs. This works like it should:
|
Paul Rowan
Member #8,612
May 2007
![]() |
Hi, I'm not that mathematical, but I have a full code list for finding the angle between 2 points, don't know if this is the same as vectors
|
|