views:

134

answers:

2

hi, how to calculate angle between two points in iphone sdk...?

A: 

When a/b are 0, you need to handle these cases separately, not just set them to one. Also, was it intended that two of your cases in the if statements add 180 to your angle. Perhaps one of these needs to be 270.

Alexander Rafferty
+3  A: 

You cannot work out an angle between 2 points. Its impossible.

What you need i a point of origin and then you are working out the angle between the lines from the origin (ox, oy) to the points (x1,y1) and (x2,y2).

So lets assume you have a proper origin point you can calculate the line as follows

v1 = (x1, y1) - (ox, oy)
v2 = (x1, y1) - (ox, oy)

v1 and v2 are therefore:

v1 = (x1 - ox, y1 - oy)
v2 = (x2 - ox, y2 - oy)

Now to work out the angle between you can use a vector property called the inner or dot product. This will return you the arccosine of the angle between the 2 / the magnitude of both vectors (v1 and v2) multiplied together.

In fact its usually easier just to normalise the 2 vectors as follows:

magnitude = sqrt( (x * x) + (y * y) );
normalvec = (x / magnitude, y / magnitude)

So v1 normalised is:

magnitude = ((x1 - ox) * (x1 - ox)) + ((y1 - oy) * (y1 - oy))
v1'       = ((x1 - ox) / magnitude, (y1 - oy) / magnitude)

and v2 normalised is:

magnitude = ((x2 - ox) * (x2 - ox)) + ((y2 - oy) * (y2 - oy))
v2'       = ((x2 - ox) / magnitude, (y2 - oy) / magnitude)

at this point I will simplify the equation writing slightly and say the 2 normalised vectors are as follows:

v1'       = (v1'x, v1'y)
v2'       = (v2'x, v2'y)

To dot product we do the following

v1' . v2' = (v1'x * v2'x) + (v1'y * v2'y)

To get the angle between these 2 vectors you then simply run that scalar value through an arccos as follows:

theta     = acos( v1'.v2' )

And you have the angle between the 2 vectors ...

Goz
I can't read it for whatever reason. Perhaps a betetr explanation of what you are doing is helpful. As it stand there is no angle between 2 points so if thats not what you mean it would be useful to re-state your question?
Goz
So why the downvote? Whats wrong with my answer? An explanation is always nice ...
Goz