如何在 Swift 中围绕其起始值上下移动 SKSpriteNode?

How do I move a SKSpriteNode up and down around its starting value in Swift?

我目前正在开发一个游戏,其中有一个 SKSpriteNode。我希望这个节点的位置一直上下移动。一开始,它应该有 y 值,例如500。然后它应该向下移动 200 像素 (500+200=700),然后它应该向上移动 400 像素 (700-400=300) 所以它就像一个上下移动,一直在 500+200 和 500-200 之间移动.我希望我的解释是可以理解的。首先,我如何获得这种效果,其次,我在哪里输入它?我应该使用自定义函数吗?我正在用 swift 编程(swift 的新手)

我写了一些示例代码,您可以根据自己的目的进行调整:

首先,你需要π来计算振荡:

// Defined at global scope.
let π = CGFloat(M_PI)

其次, 扩展 SKAction 以便您可以轻松创建将振荡相关节点的操作:

extension SKAction {

    // amplitude  - the amount the height will vary by, set this to 200 in your case.
    // timePeriod - the time it takes for one complete cycle
    // midPoint   - the point around which the oscillation occurs.

    static func oscillation(amplitude a: CGFloat, timePeriod t: Double, midPoint: CGPoint) -> SKAction {
        let action = SKAction.customActionWithDuration(t) { node, currentTime in
            let displacement = a * sin(2 * π * currentTime / CGFloat(t))
            node.position.y = midPoint.y + displacement
        }

        return action
    }
}

上面的displacement来自位移的简谐运动方程。有关更多信息,请参阅 here(他们的重新排列了一点,但它是相同的等式)。

第三, 将所有这些放在一起,在 SKScene:

override func didMoveToView(view: SKView) {
    let node = SKSpriteNode(color: UIColor.greenColor(), 
                             size: CGSize(width: 50, height: 50))
    node.position = CGPoint(x: size.width / 2, y: size.height / 2)
    self.addChild(node)

    let oscillate = SKAction.oscillation(amplitude: 200, 
                                        timePeriod: 1,
                                          midPoint: node.position)
    node.runAction(SKAction.repeatActionForever(oscillate))
}

如果您也需要在 x 轴上振荡节点,我建议向 oscillate 方法添加一个 angle 参数并使用 sincos 以确定节点应在每个轴上振荡多少。

希望对您有所帮助!