如何基于平移手势速度将angular度冲击应用于Sprite Kit节点

我在这里要做的是旋转一个SKSpriteNode围绕其锚点,并使其速度和方向与平移手势匹配。 所以如果我的平移手势是围绕精灵的顺时针方向,那么精灵顺时针旋转。

我用我的代码的问题是,它适用于精灵之下从左到右/从右到左的平底锅,但是当我尝试和垂直平移,并且它使得精灵旋转错误的方式,如果我泛精灵。

这是我到目前为止 –

let windmill = SKSpriteNode(imageNamed: "Windmill") override func didMoveToView(view: SKView) { /* Setup gesture recognizers */ let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:") self.view?.addGestureRecognizer(panGestureRecognizer) windmill.physicsBody = SKPhysicsBody(circleOfRadius: windmill.size.width) windmill.physicsBody?.affectedByGravity = false windmill.name = "Windmill" windmill.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2) self.addChild(windmill) } func handlePanGesture(recognizer: UIPanGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Changed) { pinwheel.physicsBody?.applyAngularImpulse(recognizer.velocityInView(self.view).x) } } 

我知道它不与垂直平底锅旋转的原因,我只是得到的X值,所以我想我需要结合这些莫名其妙。

我也尝试过使用applyImpulse:atPoint :,但是这会导致整个精灵被扫除。

以下步骤将基于平移手势旋转节点:

  1. 将节点中心的vector存储到平移手势的起始位置
  2. 从节点的中心到平移手势的结束位置形成一个vector
  3. 确定两个向量的叉积的符号
  4. 计算平移手势的速度
  5. 使用速度和方向对节点施加angular度冲击

这里是一个如何在Swift中执行的例子

 // Declare a variable to store touch location var startingPoint = CGPointZero // Pin the pinwheel to its parent pinwheel.physicsBody?.pinned = true // Optionally set the damping property to slow the wheel over time pinwheel.physicsBody?.angularDamping = 0.25 

声明泛处理程序方法

 func handlePanGesture(recognizer: UIPanGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { var location = recognizer.locationInView(self.view) location = self.convertPointFromView(location) let dx = location.x - pinwheel.position.x; let dy = location.y - pinwheel.position.y; // Save vector from node to touch location startingPoint = CGPointMake(dx, dy) } else if (recognizer.state == UIGestureRecognizerState.Ended) { var location = recognizer.locationInView(self.view) location = self.convertPointFromView(location) var dx = location.x - pinwheel.position.x; var dy = location.y - pinwheel.position.y; // Determine the direction to spin the node let direction = sign(startingPoint.x * dy - startingPoint.y * dx); dx = recognizer.velocityInView(self.view).x dy = recognizer.velocityInView(self.view).y // Determine how fast to spin the node. Optionally, scale the speed let speed = sqrt(dx*dx + dy*dy) * 0.25 // Apply angular impulse pinwheel.physicsBody?.applyAngularImpulse(speed * direction) } }