1

I'm trying to create a node that has the ability to be swiped offscreen. I tried adding a UIGestureRecognizer the the view but the swipe only works for the first node. I heard there is a way to subclass a spriteNode and in the touchesBegan add the ability to swipe off screen. I can setup a base for a custom sprite node but am unsure of how to give it the ability to be swiped. Here is my code for a custom sprite node:

class CustomNode: SKSpriteNode {
  init() {

    let texture = SKTexture(imageNamed: customNodeImage)
    super.init(texture: texture, color: SKColor.clear, size: texture.size())
  }

  required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

I do have a touchesBegan in my scene but when I touch a node I get a "nil" response when I try and print out the node's name. Here is my scene code:

import SpriteKit


let plankName = "woodPlank"

class PlankScene: SKScene {

  var plankWood : Plank?


  var plankArray : [SKSpriteNode] = []



  override func didMove(to view: SKView) {

    plankWood = childNode(withName: "woodPlank") as? Plank

    plankWood?.isUserInteractionEnabled = false

    let swipeRight : UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(PlankScene.swipedRight))

    swipeRight.direction = .right

    view.addGestureRecognizer(swipeRight)

  }


  func swipedRight(sender: UISwipeGestureRecognizer) {



    if sender.direction == .right {

      let moveOffScreenRight = SKAction.moveTo(x: 400, duration: 0.5)

      let nodeFinishedMoving = SKAction.removeFromParent()

      let waitForNode =   SKAction.wait(forDuration: 0.5)


      plankWood?.run(SKAction.sequence([moveOffScreenRight, nodeFinishedMoving]),
                     completion:{

      } )
    }
  }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    let touchLocation = touch!.location(in: self)

    print("\(plankWood?.name)")
      if plankWood?.name == plankName {
        print("Plank touched")
    }
  }

  override func enumerateChildNodes(withName name: String, using block: @escaping (SKNode, UnsafeMutablePointer<ObjCBool>) -> Void) {

    let swipeRight : UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(PlankScene.swipedRight))

    swipeRight.direction = .right

    view?.addGestureRecognizer(swipeRight)

  }
}
SwiftyJD
  • 5,257
  • 7
  • 41
  • 92
  • 1
    To implement touchesBegan on the node, you can just add `override func touchesBegan`... to your SKSpriteNode custom class – Nik Oct 27 '16 at 21:32
  • 1
    Did you ever looked into the link I have posted in your previous question? ;) http://stackoverflow.com/a/36524132/3402095 – Whirlwind Oct 28 '16 at 07:16

0 Answers0