gpt4 book ai didi

swift - 如何在 spritekit swift 中制作一个旋转角度的正弦波?

转载 作者:可可西里 更新时间:2023-11-01 01:14:36 26 4
gpt4 key购买 nike

我希望在我的游戏中有某种声波环绕屏幕。我可以制作直线的正弦曲线,但如何制作旋转 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com