使用Swift和SpriteKit,我想以螺旋模式移动SKSpritenode,但没有找到合适的资源让我开始。更确切地说,我想在向下循环中移动一个精灵节点。我已经检查了一系列SKActions,但由于它们不是平行执行的,因此与移动相结合的圆形运动将不起作用。我很高兴有任何提示,教程或片段让我走上正轨。
Thanx提前, 马库斯
答案 0 :(得分:5)
I've put together some sample code which you can adapt for your purposes. I've based the code off the equation for an Archimedean Spiral:
r = a + bθ
Where a
is the starting radius; b
is the radius the spiral will increase by per revolution and θ
is the current angle.
A spiral is basically a glorified circle (IMO), so to move your node in a spiral you need to be able to calculate point on a circle using an angle, radius and center point:
func pointOnCircle(#angle: CGFloat, #radius: CGFloat, #center: CGPoint) -> CGPoint {
return CGPoint(x: center.x + radius * cos(angle),
y: center.y + radius * sin(angle))
}
Next, extend SKAction
so you can easily create a spiral action:
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
}
}
Finally, an example of use. In 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 :(得分:2)
虽然上面提到的解决方案很精彩,但有一种更简单的方法。