使用 Swift 向下循环移动 SKSpriteNode

Moving a SKSpriteNode in a downward loop, using Swift

使用 Swift 和 SpriteKit,我想以螺旋模式移动 SKSpritenode,但没有找到合适的资源让我开始。更准确地说,我想在向下循环中移动一个精灵节点。我已经检查了一系列 SKActions,但由于它们不是并行执行的,因此结合移动到的圆周运动将不起作用。如果有任何提示、教程或片段让我走上正轨,我会很高兴。

提前致谢, 马库斯

我整理了一些示例代码,您可以根据自己的目的进行调整。我将代码基于 Archimedean Spiral:

的等式
r = a + bθ

其中a为起始半径; b 是螺旋每转增加的半径,θ 是当前角度。

螺旋基本上是一个美化的圆(IMO),因此要在螺旋中移动节点,您需要能够使用角度、半径和中心点计算圆上的点:

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)

虽然上面提到的解决方案非常出色,但还有一种更简单的方法。

  1. 添加一个 spinnerNode,并使用 rotateBy
  2. 重复旋转它
  3. 将您的精灵作为 child 添加到 spinnerNode(默认情况下,您的精灵将随 spinnerNode 一起旋转)
  4. 将您的 spriteNode(使用 moveTo)移动到 wheelNode 的中心(您的 sprite 将以螺旋路径向中心移动)