How would you calculate the degrees between two points on the edge of a circle in Swift.
Asked
Active
Viewed 1.2k times
16
-
Do you know for sure this is a circle? Like, you know the center of the circle? Because two points does not a circle make, since an infinite number of different circles can be desecribed by two points - you need a third, either on the circle or the origin. – corsiKa Feb 21 '15 at 02:39
-
i know the origin also @corsiKa – PoKoBros Feb 21 '15 at 02:45
-
So then you can just use arctan(delta y/delta x). I don't know what swift sprite key is, so I would not be sure of the format for the code for that. Edit: most programming languages using trig uses radians, so your output might be in radians. If there's a function to convert it to degrees, just use that; otherwise, use the formula to convert it to degrees which is rads*180/pi – Muhatashim Feb 21 '15 at 03:12
1 Answers
39
Given points p1
, p2
on a circle with center center
,
you would compute the difference vectors first:
let v1 = CGVector(dx: p1.x - center.x, dy: p1.y - center.y)
let v2 = CGVector(dx: p2.x - center.x, dy: p2.y - center.y)
Then
let angle = atan2(v2.dy, v2.dx) - atan2(v1.dy, v1.dx)
is the (directed) angle between those vectors in radians, and
var deg = angle * CGFloat(180.0 / M_PI)
the angle in degrees. The computed value can be in the range -360 .. 360, so you might want to normalize it to the range 0 <= deg < 360 with
if deg < 0 { deg += 360.0 }

Martin R
- 529,903
- 94
- 1,240
- 1,382
-
will this code work on an iPad? all that is going to happen is that the circle will enlarge a little bit. – PoKoBros Feb 22 '15 at 04:15
-
4@PoKoBros: This is just math, it works on any device. It only computes an angle, so what do you mean by "the circle will enlarge a bit" ? – Martin R Feb 22 '15 at 07:01
-
-
@PoKoBros: Sorry, I don't get it. This question was about computing an angle from three points (center, p1, p2). The radius is not even involved in the formula. So how/where does the *"radius double on an iPad"*? – Martin R Feb 22 '15 at 15:22
-
For some reason when I try the same exact code on the iPad, it does not work. – PoKoBros Feb 22 '15 at 16:24
-
@PoKoBros: Can you provide a concrete example of input values, actual output and expected output? – Martin R Feb 22 '15 at 16:25
-
I actually only needed to calculate up to radians not degrees so I stopped at the let angle line in your answer. I guess what I am trying to ask is that shouldn't the radians outputted be the same in all circles? – PoKoBros Feb 22 '15 at 16:36
-
Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/71433/discussion-between-pokobros-and-martin-r). – PoKoBros Feb 22 '15 at 17:35