views:

163

answers:

2

Given P1 and P2, how can I get the angle from P1 to P2? Thanks

A: 

Ok remembering high school trig. this is what I get.

Two points are A(x1,y1) and B(x2,y2)

I assume you want the angle between the two points and the origin O(0,0).

Well each point makes a triangle bounded by its height, its base and its hypotenuse, so you get two angles alpha1 and alpha2. The idea is to find each of these and compute your required angle beta, by doing beta = alpha1 - alpha2 where alpha1 is such that alpha1 > alpha2.

Compute alpha1 = inv_tan(y1/x1) and alpha2 = inv_tan(y2/x2)

then do beta = alpha1 - alpha2

Ankur
The other answers amount to the same thing but are more concise.
Ankur
+2  A: 

It's just float angle = atan2(p1.y - p2.y, p1.x - p2.x).

Of course the return type is in radians, if you need it in degrees just do angle * 180 / PI

Jack
That function takes `y` first.
GMan
yep, fixed.. just in time to notify that they cloned my answer :)
Jack