TouchEvents in watchOS 3 SpriteKit?

落爺英雄遲暮 提交于 2020-01-23 07:41:34

问题


When using SpriteKit in watchOS 3, how do you handle the touch events? I am porting the SpriteKit games from iOS and the codes below won't work. Or you have to control the WKInterfaceController somehow?

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?)  {}

回答1:


After a lot of frustration with the same issue, I wound up using gesture recognizers, and calculating the position from there.

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

One tip though: A strange bug I found though when creating the method to handle the gesture recognizer was that the gesture wasn't being passed by default into the method. I had to ctrl + drag to create the method, and then modify the signature to contain the gesture. If I created the method with the gesture in the signature, Xcode wouldn't allow me to attach the gesture recognizer to it.

It would seem that there would be a better way to detect the touches, but that's the workaround I found for now.




回答2:


To get something close to touch down events use a WKLongPressGestureRecognizer with super-short duration (0.001). The IBAction connected to this recognizer will get touch down events pretty much right away. The location is found in the locationInObject property of the recognizer. If the goal is to get moving touches then use the pan recognizer.




回答3:


So to do this I first hooked up a gesture recognizer in the watch storyboard. Created an IBAction, then called a method on the SpriteKit Scene passing in gesture.locationInObject(). Then within the scene method for the conversion, here's some code.

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))

The newX and newY are the touch coordinates in the scene.



来源:https://stackoverflow.com/questions/38137178/touchevents-in-watchos-3-spritekit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!