看下面的代码
让我们定义你的精灵和目标点
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))
旋转+移动扩展
对于后跟移动动画的旋转动画,您可以使用此扩展程序
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。