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

倾然丶 夕夏残阳落幕 提交于 2019-12-23 16:53:43

问题


I'm currently working on a game, where there's a SKSpriteNode. I want, that this node's location moves up and down all the time. At the beginning, it should have the y value e.g. 500 . Then it should move 200 px down (500+200=700) and then it should move 400 up (700-400=300) so it creates like a up and down, which travels between 500+200 and 500-200 all the time. I hope I explained it understandable. First, how do I get this effect and second, where do I enter it? Should I use a custom func? I'm programming with swift (newbie to swift)


回答1:


I've written a some sample code which you can adapt for your purposes:

Firstly, you need π for the oscillation calculations:

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

Secondly, extend SKAction so you can easily create actions that will oscillate the node in question:

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
    }
}

The displacement above comes from the Simple Harmonic Motion equation for displacement. See here for more information (their's is a rearranged a little, but it's the same equation).

Thirdly, putting all that together, in the 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))
}

If you needed to oscillate the node in the x-axis too I'd recommend adding an angle argument to the oscillate method and using sin and cos to determine how much the node should oscillate in each axis.

Hope that helps!



来源:https://stackoverflow.com/questions/30177117/how-do-i-move-a-skspritenode-up-and-down-around-its-starting-value-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!