<Description> : Implementing CGFloat shortest angle distance in radians.
<Type> : feature.
This commit is contained in:
parent
8e92a2265f
commit
1e1c5aa718
|
@ -66,4 +66,34 @@ class CGFloatTests: XCTestCase {
|
|||
XCTAssertGreaterThanOrEqual(randomClosedCGFloat, 0.0)
|
||||
XCTAssertLessThanOrEqual(randomClosedCGFloat, 10.0)
|
||||
}
|
||||
|
||||
func testShortestAngleBetweenInRadiansSanityTest() {
|
||||
let firstAngle = CGFloat(0)
|
||||
let secondAngle = CGFloat(1)
|
||||
|
||||
let shortestAngle = CGFloat.shortestAngleInRadians(from: firstAngle, to: secondAngle)
|
||||
XCTAssertNotNil(shortestAngle)
|
||||
|
||||
XCTAssertEqual(shortestAngle, secondAngle - firstAngle)
|
||||
}
|
||||
|
||||
func testShortestAngleFullCirclePi() {
|
||||
let firstAngle = CGFloat(0)
|
||||
let fullCircleAngle = CGFloat(2 * Double.pi)
|
||||
|
||||
let shortestAngle = CGFloat.shortestAngleInRadians(from: firstAngle, to: fullCircleAngle)
|
||||
XCTAssertNotNil(shortestAngle)
|
||||
|
||||
XCTAssertEqual(shortestAngle, 0)
|
||||
}
|
||||
|
||||
func testShortestAngleThreeFourthsCirclePi() {
|
||||
let firstAngle = CGFloat(0)
|
||||
let threeFourthsCircleAngle = CGFloat(1.5 * Double.pi)
|
||||
|
||||
let shortestAngle = CGFloat.shortestAngleInRadians(from: firstAngle, to: threeFourthsCircleAngle)
|
||||
XCTAssertNotNil(shortestAngle)
|
||||
|
||||
XCTAssertEqual(shortestAngle, -0.5 * .pi)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -62,4 +62,22 @@ extension CGFloat {
|
|||
public static func random(within: ClosedRange<CGFloat>) -> CGFloat {
|
||||
return CGFloat.random() * (within.upperBound - within.lowerBound) + within.lowerBound
|
||||
}
|
||||
|
||||
/**
|
||||
EZSE :Returns the shortest angle between two angles. The result is always between
|
||||
-π and π.
|
||||
|
||||
Inspired from : https://github.com/raywenderlich/SKTUtils/blob/master/SKTUtils/CGFloat%2BExtensions.swift
|
||||
*/
|
||||
public static func shortestAngleInRadians(from first: CGFloat, to second: CGFloat) -> CGFloat {
|
||||
let twoPi = CGFloat(.pi * 2.0)
|
||||
var angle = (second - first).truncatingRemainder(dividingBy: twoPi)
|
||||
if (angle >= .pi) {
|
||||
angle = angle - twoPi
|
||||
}
|
||||
if (angle <= -.pi) {
|
||||
angle = angle + twoPi
|
||||
}
|
||||
return angle
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue