我在这里要做的是围绕其锚点旋转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 :,但这会导致整个精灵被扫除。
答案 0 :(得分:2)
以下步骤将根据平移手势旋转节点:
以下是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
声明pan处理程序方法
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)
}
}