2016-10-24 77 views
1

好吧,目前在我的遊戲中,我可以拖動,滑動並輕拂節點。但是,我希望用戶只能輕掃/輕拂節點,並且我不希望用戶能夠拖動節點。我怎樣才能做到這一點?如何在不拖動的情況下輕彈/滑動精靈?

這裏是我當前的代碼:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 

    for touch in touches { 
     let location = touch.location(in: self) 

     if ball.frame.contains(location) { 
      touchPoint = location 
      touching = true 
     } 
    } 
} 

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 
    let touch = touches.first as UITouch! 
    let location = touch!.location(in: self) 
    touchPoint = location 

    for touch in touches { 
     let location = touch.location(in: self) 
     touchPoint = location 
     if touching { 
      if touchPoint != ball.position { 
       let dt:CGFloat = 1.0/60.0 
       let distance = CGVector(dx: touchPoint.x-ball.position.x, dy: touchPoint.y-ball.position.y) 
       let velocity = CGVector(dx: distance.dx/dt, dy: distance.dy/dt) 
       ball.physicsBody!.velocity=velocity 
      } 
     } 
    } 
} 

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    touching = false 

    for touch in touches { 
     let location = touch.location(in: self) 
     touchPoint = location 
     let node = self.atPoint(location) 
    } 
} 
+0

請定義更清楚你想達到什麼。 – matthiaswitt

+0

我在猜測:你的目標是讓節點不動,直到手指從滑動手勢釋放爲止,此時手指在屏幕上的移動速度和距離決定了節點的移動速度和方向? – Confused

回答

1

這就是爲什麼UIGestureRecognizers存在。在您的視圖中添加UIPanGestureRecognizer,並使用velocity(in:UIView)方法讓您知道輕彈的方向和速度。

請注意,如果您只使用手勢,則無法將手勢放在節點上,只能查看視圖,因此您需要將視圖座標轉換爲場景座標。

您還可以讓手勢觸摸到場景,以允許正常的觸摸呼叫,並使用平移手勢的速度。

https://developer.apple.com/reference/uikit/uipangesturerecognizer