使用Swift和SpriteKit,我想让一个SKSpritenode以螺旋形式移动,但没有找到合适的资源来帮助我入门。更准确地说,我想让一个精灵节点以向下的循环方式移动。我已经检查了一系列的SKActions,但由于它们不是并行执行的,所以结合move-to的圆形运动将无法实现。如果有任何提示、教程或片段能够帮我找到正确的方向,我将不胜感激。
提前感谢, 马库斯
提前感谢, 马库斯
我已经准备好一些示例代码,您可以根据自己的需要进行调整。这段代码基于一个阿基米德螺旋线方程:
r = a + bθ
其中a
是起始半径;b
是每个旋转增加的半径;而θ
是当前角度。
螺旋线基本上是一个美化过的圆(在我看来),因此要使您的节点在螺旋线上移动,需要能够使用角度、半径和中心点计算圆上的点:
func pointOnCircle(#angle: CGFloat, #radius: CGFloat, #center: CGPoint) -> CGPoint {
return CGPoint(x: center.x + radius * cos(angle),
y: center.y + radius * sin(angle))
}
SKAction
以便您可以轻松创建螺旋动作:extension SKAction {
static func spiral(#startRadius: CGFloat, endRadius: CGFloat, angle
totalAngle: CGFloat, centerPoint: CGPoint, duration: NSTimeInterval) -> SKAction {
// The distance the node will travel away from/towards the
// center point, per revolution.
let radiusPerRevolution = (endRadius - startRadius) / totalAngle
let action = SKAction.customActionWithDuration(duration) { node, time in
// The current angle the node is at.
let θ = totalAngle * time / CGFloat(duration)
// The equation, r = a + bθ
let radius = startRadius + radiusPerRevolution * θ
node.position = pointOnCircle(angle: θ, radius: radius, center: centerPoint)
}
return action
}
}
didMoveToView
中:let node = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 10, height: 10))
node.position = CGPoint(x: size.width / 2, y: size.height / 2)
addChild(node)
let spiral = SKAction.spiral(startRadius: size.width / 2,
endRadius: 0,
angle: CGFloat(M_PI) * 2,
centerPoint: node.position,
duration: 5.0)
node.runAction(spiral)
虽然上述解决方案想法高妙,但还有更简单的方法。