我想在一个圆上创建X点的30度度数。像这样:
我现在拥有的代码如下:
func pointsOnCircle(num: Int, radius:Float, center:CGPoint) {
let _by = 360/num
for i in stride(from: 0, to: 360, by: _by) {
print("Stride: \(i)")
let x = radius * cos(Float(i))
let y = radius * sin(Float(i))
let pos = CGPoint(x: CGFloat(x)+center.x, y: CGFloat(y)+center.y)
var node: SKSpriteNode!
if(i == 0){
node = SKSpriteNode(color: SKColor.blue, size: CGSize(width: 10, height: 10))
} else if (i == 90){
node = SKSpriteNode(color: SKColor.orange, size: CGSize(width: 10, height: 10))
} else if (i == 180){
node = SKSpriteNode(color: SKColor.purple, size: CGSize(width: 10, height: 10))
} else {
node = SKSpriteNode(color: SKColor.red, size: CGSize(width: 10, height: 10))
}
node.alpha = 0.5
node.position = pos
node.zPosition = 20
self.addChild(node)
}
}
由于360除以12是30。我这样调用该函数:
pointsOnCircle(num: 12, radius: 100, center: CGPoint(x: frame.midX, y: frame.midY))
但是,如您在下图所示,我没有得到期望的结果:
蓝色矩形是0度,这是正确的
紫色矩形是180度,不正确
橙色矩形为90度,这也是错误的。
答案 0 :(得分:-2)
Helper函数将度数转换为弧度
Knight0fDragon的编辑-来源:How can I convert from degrees to radians?谢谢@LeoDabus提供了精彩的扩展。
extension BinaryInteger {
var degreesToRadians: CGFloat { return CGFloat(self) * .pi / 180 }
}
extension FloatingPoint {
var degreesToRadians: Self { return self * .pi / 180 }
var radiansToDegrees: Self { return self * 180 / .pi }
}
结果
45.degreesToRadians // 0.785398163397448
Int(45).degreesToRadians // 0.785398163397448
Int8(45).degreesToRadians // 0.785398163397448
Int16(45).degreesToRadians // 0.785398163397448
Int32(45).degreesToRadians // 0.785398163397448
Int64(45).degreesToRadians // 0.785398163397448
UInt(45).degreesToRadians // 0.785398163397448
UInt8(45).degreesToRadians // 0.785398163397448
UInt16(45).degreesToRadians // 0.785398163397448
UInt32(45).degreesToRadians // 0.785398163397448
UInt64(45).degreesToRadians // 0.785398163397448
Double(45).degreesToRadians // 0.7853981633974483
CGFloat(45).degreesToRadians // 0.785398163397448
Float(45).degreesToRadians // 0.7853981
Float80(45).degreesToRadians // 0.785398163397448278999