将精灵旋转到一个点并在一段时间内将其移动到该点

Rotating a sprite towards a point and move it towards it with a duration

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

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

我如何制作一个 point/sprite/shape 它会首先旋转然后朝向它移动(而不是朝向它),持续时间为 1 秒。

看下面代码

让我们定义您的精灵和目标点

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

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

的增量 space
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))

旋转 + 移动扩展

对于移动动画后的旋转动画,您可以使用此扩展程序

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)
    }
}

Thanks to Wikipedia for the image.