我正在开发一个游戏,其中有一个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
}
}
上述的位移
来自于简谐运动的位移方程。点击这里了解更多信息(他们的公式稍微重新排列了一下,但是是相同的方程)。
第三个问题:将所有内容整合,在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))
}
oscillate
方法添加一个angle
参数,并使用sin
和cos
来确定节点在每个轴上的振荡程度。SKAction
,但是我自己还没有在那些情况下测试过。不过很高兴知道我能帮到你! :) - ABakerSmith
SKAction
来实现。 - ABakerSmith