TouchEvents in watchOS 3 SpriteKit?

北战南征 提交于 2019-12-05 16:03:08

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.

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.

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.

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