我希望在我的游戏中屏幕上有某种声波。我可以制作直线的正弦,但是如何制作旋转 20 度的正弦呢?例如,从左下角到右上角?
let pi = CGFloat.pi
let wave = Waves[0]
let x = path.currentPoint.x
let c = (2 * pi) / (wave.Wavelength * 30)
let a = 30 * wave.Amplitude
let y = a * sin(c * x)
path.addLine(to: CGPoint(x: x + 2, y: y ))
最佳答案
您可以使用 2 Bézier curves 制作一个非常准确地近似正弦波的 UIBezierPath
:
/// Make a path that approximates a peak-to-peak sine wave
func sinePath(size: CGSize) -> UIBezierPath {
let path = UIBezierPath()
// path starts at 0,0
path.move(to: CGPoint.zero)
let halfWidth = size.width / 2.0
// base x-values for control points
// baseX approximates the best fit Bézier curve for a sine wave
let baseX: = CGFloat(0.3642124232)
let firstX = halfWidth * baseX
let secondX = halfWidth * (1.0 - baseX)
// curve from start peak to trough
path.addCurve(to: CGPoint(x: halfWidth, y: size.height),
controlPoint1: CGPoint(x: firstX , y: 0),
controlPoint2: CGPoint(x: secondX, y: size.height))
// curve from trough to end peak
path.addCurve(to: CGPoint(x: size.width, y:0),
controlPoint1: CGPoint(x: size.width - secondX, y: size.height),
controlPoint2: CGPoint(x: size.width - firstX , y: 0))
return path
}
然后您可以使用 CGAffineTransform
旋转它,如下所示:
/// Convert degrees to radians
func degreeToRadian(_ angle: CGFloat) -> CGFloat {
return angle * CGFloat.pi / 180.0
}
let path = sinePath(size: CGSize(width: 200.0, height: 100.0))
path.apply(CGAffineTransform(rotationAngle: degreeToRadian(20)))
我从这个问题中得到了baseX
常量:
How to approximate a half-cosine curve with bezier paths in SVG?
关于swift - 如何在 spritekit swift 中制作一个旋转角度的正弦?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46427748/