简体   繁体   中英

Add gesture to SKShapeNode in WatchOS3

I am able to add gesture in SpriteKit Scene. But not able to add gesture to one of my node in the scene.

Also, touchesBegan method is not available in WatchKit . So added gestureRecognizer in my interface and pass it in the SpriteKit Scene.

But this lead to add panGesture to the whole scene instead of my node.

Is there any way to add the gesture to only one of my node?

You do not add gestures to nodes ever.

You can only add gestures to anything that can recognize a gesture.

In UIKit, these are UIViews

In Watchkit, these are WKInterfaces

Now what you want to do in Watchkit, is when a gesture starts, detect if you are touching a node

you can do this in Watchkit by getting the location with locationinObject and converting it to the scene coordinate system with scene by doing :

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

What this does is get your position in the the interface, then convert it over to the scene by flipping the y axis, and then adjusting for the difference of the scene's width to the interface width.

now to use this, you simply call it whenever you are in your recognizer method, and check whether or not the node you are touching is your node

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM