使用Swift将SKSpriteNode在向下循环移动

4
使用Swift和SpriteKit,我想让一个SKSpritenode以螺旋形式移动,但没有找到合适的资源来帮助我入门。更准确地说,我想让一个精灵节点以向下的循环方式移动。我已经检查了一系列的SKActions,但由于它们不是并行执行的,所以结合move-to的圆形运动将无法实现。如果有任何提示、教程或片段能够帮我找到正确的方向,我将不胜感激。
提前感谢, 马库斯

看一下斐波那契数列和黄金螺旋,这提供了一些不同的绘图方法,但并不特定于编程。 - Brennan Adler
2个回答

5

我已经准备好一些示例代码,您可以根据自己的需要进行调整。这段代码基于一个阿基米德螺旋线方程

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)

2

虽然上述解决方案想法高妙,但还有更简单的方法。

  1. 添加一个spinnerNode,并使用rotateBy重复旋转它
  2. 将你的精灵作为spinnerNode的子节点添加(你的精灵默认会随着spinnerNode一起旋转)
  3. 移动你的spriteNode(使用moveTo)到wheelNode的中心(你的精灵将呈螺旋形路径向中心运动)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接