如何子类化SKSpriteNode并实现touchesBegan?

时间:2016-10-27 20:42:41

标签: ios swift sprite-kit skspritenode

我正在尝试创建一个能够在屏幕外滑动的节点。我尝试在视图中添加UIGestureRecognizer,但滑动仅适用于第一个节点。我听说有一种方法可以将spriteNode子类化,并在touchesBegan中添加滑动屏幕的功能。我可以为自定义精灵节点设置一个基础,但我不确定如何赋予它刷卡的能力。这是我的自定义精灵节点的代码:

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

我的场景中确实有一个touchesBegan但是当我触摸一个节点时,我会得到一个" nil"我尝试打印出节点名称时的响应。这是我的场景代码:

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)

  }
}

0 个答案:

没有答案