Get angle from 2 positions

后端 未结 6 1244
失恋的感觉
失恋的感觉 2020-12-08 15:18

I have 2 objects and when I move one, I want to get the angle from the other.

For example:

Object1X = 211.000000, Object1Y = 429.000000
Object2X = 24         


        
6条回答
  •  Happy的楠姐
    2020-12-08 15:57

    Here's how I'm doing it in Swift for those interested, it's based on @bshirley's answer above w/ a few modifications to help match to the calayer rotation system:

    extension CGFloat {
        var degrees: CGFloat {
            return self * CGFloat(180) / .pi
        }
    }
    
    extension CGPoint {
        func angle(to comparisonPoint: CGPoint) -> CGFloat {
            let originX = comparisonPoint.x - x
            let originY = comparisonPoint.y - y
            let bearingRadians = atan2f(Float(originY), Float(originX))
            var bearingDegrees = CGFloat(bearingRadians).degrees
    
            while bearingDegrees < 0 {
                bearingDegrees += 360
            }
    
            return bearingDegrees
        }
    }
    

    This provides a coordinate system like this:

            90
    180              0
            270
    

    Usage:

    point.angle(to: point2)
    CGPoint.zero.angle(to: CGPoint(x: 0, y: 1)) // 90
    

提交回复
热议问题