簡體   English   中英

如何在Swift中圍繞其起始值上下移動SKSpriteNode?

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

我正在開發一款游戲,其中有一個SKSpriteNode。 我想,這個節點的位置一直在上下移動。 一開始,它應該具有y值,例如500。 然后它應該向下移動200 px(500 + 200 = 700)然后它應該向上移動400(700-400 = 300),因此它會像上下一樣產生,一直在500 + 200到500-200之間移動。 我希望我解釋它是可以理解的。 首先,我如何獲得此效果,其次,我在哪里輸入? 我應該使用自定義功能嗎? 我用swift編程(newbie to 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來自用於位移的簡諧運動方程。 請參閱此處了解更多信息(它們的重新排列有點,但它是相同的等式)。

第三,將所有這些放在一起,在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來確定節點應該在每個軸上振盪多少。

希望有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM