calculating angle between two points on edge of circle Swift SpriteKit

前端 未结 1 793
我寻月下人不归
我寻月下人不归 2021-02-07 15:41

How would you calculate the degrees between two points on the edge of a circle in Swift.

\"enter

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-07 16:30

    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 }
    

    0 讨论(0)
提交回复
热议问题