[英]How do I move a SKSpriteNode up and down around its starting value in Swift?
I'm currently working on a game, where there's a SKSpriteNode. 我正在开发一款游戏,其中有一个SKSpriteNode。 I want, that this node's location moves up and down all the time.
我想,这个节点的位置一直在上下移动。 At the beginning, it should have the y value eg 500 .
一开始,它应该具有y值,例如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.
然后它应该向下移动200 px(500 + 200 = 700)然后它应该向上移动400(700-400 = 300),因此它会像上下一样产生,一直在500 + 200到500-200之间移动。 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)
我用swift编程(newbie to swift)
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: 其次,扩展
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
}
}
The displacement
above comes from the Simple Harmonic Motion equation for displacement. 上面的
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
: 第三,将所有这些放在一起,在
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. 如果你需要在x轴上振荡节点,我建议在
oscillate
方法中添加一个angle
参数,并使用sin
和cos
来确定节点应该在每个轴上振荡多少。
Hope that helps! 希望有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.