2017-02-28 65 views
3

我可以在SpriteKit場景中添加手勢。但是無法爲場景中的一個節點添加手勢。在WatchOS3中向SKShapeNode添加手勢

另外,touchesBegan方法在WatchKit中不可用。所以在我的界面中添加了gestureRecognizer並將它傳遞給了SpriteKit場景。

但是這導致panGesture添加到整個場景,而不是我的節點。

有什麼辦法可以將手勢添加到我的一個節點上嗎?

回答

1

您不會爲節點添加手勢。

只能將手勢添加到可識別手勢的任何內容。

UIKit中,這些都是UIViews

在Watchkit,這些都是WKInterfaces

現在你想在Watchkit做什麼,是一種姿態開始時,檢測,如果你觸摸節點

您可以在Watchkit中通過獲取locationinObject的位置並將其轉換爲具有場景的場景座標系來做到這一點:

extension WKGestureRecognizer { 
    var position : CGPoint 
    { 
     get 
     { 
      let location = locationInObject() 
      let bounds = objectBounds() 
      let dWidth = self.scene.size.width/bounds.size.width 
      let dHeight = self.scene.size.height/bounds.size.height 
      let x = (location.x * dWidth) - scene.width * scene.anchorPoint.x) 
      let y = (bounds.maxY - location.y) * dHeight - (scene.height * scene.anchorPoint.y) 
      return CGPoint(x:x, y:y) 
     } 
    } 
} 

這樣做是在界面中獲取位置,然後通過翻轉y軸將其轉換到場景,然後調整場景寬度與界面寬度的差異。

現在使用這個,你只需要調用它,只要你在你的識別方法,並檢查你是感人的節點是否是您的節點

func didPan(_ recognizer: WKPanGestureRecognizer) { 
     switch(recognizer.state) 
     { 
      case .began: 
       let scenePosition = recognizer.position 
       let node = scene.atPoint(scenePosition) 
       guard let node = shapeNode else {return} 
       //allow pan, so make a note or something 
      case //do other cases here 
     } 
}