首页 > 解决方案 > 将 SKNode 作为函数的参数传递时出错

问题描述

我正在尝试将 SKNode 作为函数的参数传递,因此我可以访问 SKNode 的属性,例如函数中的位置/p。

class GameScene: SKScene {


     let node = SKShapeNode()
     let swipeRightRec = UISwipeGestureRecognizer()
     var pathToDraw = CGMutablePath()


     override func didMove(to view: SKView) {

        pathToDraw.move(to: CGPoint(x: 100.0, y: 100.0))
        pathToDraw.addLine(to: CGPoint(x: 125.0, y: 50.0))
        node.path = pathToDraw

        //trying to pass created node in the swipedRight function
        swipeRightRec.addTarget(self, action: #selector(GameScene.swipedRight(node)))
        swipeRightRec.direction = .right
        self.view!.addGestureRecognizer(swipeRightRec)
     }

      // the swipe right function that accepts a SKShapeNode
      @objc func swipedRight(node: SKShapeNode) {
         let path = node.path
      }

}

我收到的错误是:

实例成员 'swipedRight' 不能用于类型 'GameScene';你的意思是使用这种类型的值吗?

标签: swiftsprite-kit

解决方案


在目标/动作模式中,任何动作的(第一个)参数都必须是执行动作的对象

@objc func swipedRight(_ sender: UISwipeGestureRecognizer) { ... }

并仅使用方法名称添加选择器

swipeRightRec.addTarget(self, action: #selector(swipedRight))

但是由于节点无论如何都是一个属性,所以没有必要将它作为参数传递。


推荐阅读