将精灵旋转到一个点并以持续时间向它移动

时间:2016-07-16 13:03:49

标签: swift sprite-kit touch

所以,如果我有类似的东西:

class game: SKScene {
    let sprite = SKSpriteNode(imageNamed: "sprite")
}

如何制作一个点/精灵/形状,它首先会朝着它移动,然后向它移动(而不是它),持续时间为1秒。

1 个答案:

答案 0 :(得分:6)

请查看以下代码

让我们定义你的精灵和目的地点

let sprite = SKSpriteNode(imageNamed: "mario.png")
let destPoint = CGPoint(x: 10, y: 10)

现在让我们定义2个向量。第一个(v1)是垂直向量。第二个(v2)表示精灵和目标点的增量空间

let v1 = CGVector(dx:0, dy:1)
let v2 = CGVector(dx:destPoint.x - sprite.position.x, dy: destPoint.y - sprite.position.y)

现在我计算这两个矢量之间的角度

let angle = atan2(v2.dy, v2.dx) - atan2(v1.dy, v1.dx)

并将其指定给精灵

sprite.zRotation = angle

扩展

我将代码封装在扩展名

extension SKNode {
    func rotateVersus(destPoint: CGPoint) {
        let v1 = CGVector(dx:0, dy:1)
        let v2 = CGVector(dx:destPoint.x - position.x, dy: destPoint.y - position.y)
        let angle = atan2(v2.dy, v2.dx) - atan2(v1.dy, v1.dx)
        zRotation = angle
    }
}

所以现在你可以做到

let sprite = SKSpriteNode(imageNamed: "mario.png")
sprite.rotateVersus(CGPoint(x: 10, y: 10))

enter image description here

旋转+移动扩展

对于旋转动画后跟移动动画,您可以使用此扩展名

extension SKNode {
    func rotateVersus(destPoint: CGPoint, durationRotation: NSTimeInterval, durationMove: NSTimeInterval) {
        let v1 = CGVector(dx:0, dy:1)
        let v2 = CGVector(dx:destPoint.x - position.x, dy: destPoint.y - position.y)
        let angle = atan2(v2.dy, v2.dx) - atan2(v1.dy, v1.dx)

        let rotate = SKAction.rotateToAngle(angle, duration: durationRotation)
        let move = SKAction.moveBy(CGVector(dx: v2.dx * 0.9, dy: v2.dy * 0.9), duration: durationMove)
        let sequence = SKAction.sequence([rotate, move])
        self.runAction(sequence)
    }
}
  

感谢维基百科image