2014-10-27 46 views
1

我在這裏要做的是在其錨點周圍旋轉SKSpriteNode,並使其速度和方向與平移手勢相匹配。因此,如果我的平移手勢是圍繞精靈順時針旋轉,那麼精靈順時針旋轉。如何根據平移手勢速度將角衝量應用於Sprite Kit節點

我的代碼存在的問題是,它對於從左到右/從右到左的精靈下面的平鋪很有用,但是當我嘗試垂直平移時它並不會完全平移,並且它會使精靈旋轉錯誤我在精靈之上平移。

這裏就是我這麼遠 -

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:,但這會導致整個精靈被掃除。

回答

2

下面的步驟將旋轉基於平移姿勢的節點:

  1. 存儲從節點的中心到平移姿勢
  2. 的起始位置的向量形式從的中心的矢量節點到平移姿勢
  3. 的結束位置確定兩個向量
  4. 的交叉乘積的符號計算平移手勢的速度
  5. 應用角衝到節點使用速度和方向

這裏有一個如何做,在斯威夫特的例子...

// 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) 
    } 
} 
相關問題