2016-07-01 54 views
3

在watchOS 3中使用SpriteKit時,如何處理觸摸事件?我正在從iOS移植SpriteKit遊戲,下面的代碼不起作用。或者你必須以某種方式控制WKInterfaceController?watchOS 3中的TouchEvents SpriteKit?

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

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

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

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

回答

3

經過很多挫折與同樣的問題後,我用手勢識別器結束,並從那裏計算的位置。

@IBAction func handleSingleTap(tapGesture: WKTapGestureRecognizer) { 
    let location = tapGesture.locationInObject() 
    if yourSpriteNodeRect.contains(location) { 
     //do stuff 
    } 
} 

一個提示,但:一個奇怪的錯誤,我發現,雖然創建於處理手勢識別方法時是手勢沒有被默認傳遞到方法。我不得不按Ctrl +拖動來創建方法,然後修改簽名以包含手勢。如果我使用簽名中的手勢創建了方法,Xcode將不允許我將手勢識別器附加到它。

似乎有更好的方法來檢測觸摸,但這是我現在找到的解決方法。

+0

你可以做我修改簽名的方法,或者你可以保留它並添加一個保護語句:@IBAction func panRecognized(_ sender:AnyObject){{0} {0} {0}保護讓panGesture = sender as? WKPanGestureRecognizer其他{ return } –

+0

確實如此,但文檔(https://developer.apple.com/reference/watchkit/wkgesturerecognizer)允許這兩種類型的簽名。守衛聲明應該是必要的。 IBAction func handleGesture()/ IBAction func handleGesture(gestureRecognizer:WKGestureRecognizer) – LMVogel

+0

識別器增加觸摸延遲是非常煩人的。取決於遊戲的類型 – matthiaswitt

0

爲了獲得接近觸及事件的東西,請使用具有超短持續時間(0.001)的WKLongPressGestureRecognizer。連接到這個識別器的IBAction幾乎馬上就會發生觸發事件。該位置位於識別器的locationInObject屬性中。如果目標是移動觸摸,然後使用平移識別器。

property settings in Interface Builder

0

因此,要做到這一點我在腕錶故事板第一迷上了一個手勢識別。創建了IBAction,然後在gesture.locationInObject()中傳入SpriteKit場景中的方法。然後在轉換的場景方法中,這裏是一些代碼。

let screenBounds = WKInterfaceDevice.current().screenBounds 
let newX = ((location.x/screenBounds.width) * self.size.width) - (self.size.width/2) 
let newY = -(((location.y/screenBounds.height) * self.size.height) - (self.size.height/2)) 

newX和newY是場景中的觸摸座標。