简体   繁体   中英

Add Gesture Recognizer to SKShapeNode Swift 4

I would like a function to be executed when a user scrolls up on an SKShapeNode.

I can do it for the whole view using the following code:

let swipeUp:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedUp:"))
swipeUp.direction = .up
view?.addGestureRecognizer(swipeUp);

How do I modify this code to work for an SKShapeNode. Thanks

Normally you cannot add a gesture recognizer to an instance of SKScene because the class is not part of UIKit . But since you have added your gesture recognizer to the view, you can use a separate handler method to respond to the swipe gestures.

override func didMove(to view: SKView) {
    let swipeUpGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.handleSwipeFrom))
    self.view!.addGestureRecognizer(swipeUpGestureRecognizer)
}

@objc func handleSwipeFrom(_ recognizer: UISwipeGestureRecognizer) {
    switch recognizer.state {
    case .changed:
        if recognizer.direction == .up {
            let touchInView = recognizer.location(in: recognizer.view)
            let touch = convertPoint(fromView: touchInView)
            let nodeArray = nodes(at: touch)
            for node in nodeArray {
                if node.name == "my shape node" {
                    // You've got a reference to your shape node and can take some action here (add movement or whatever)
                }
            }
        }
    default:
        return
    }
}

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