【问题标题】:UILongPressGestureRecognizer with SpriteKit带有 SpriteKit 的 UILongPressGestureRecognizer
【发布时间】:2017-07-03 19:46:49
【问题描述】:

我试图弄清楚如何检测 shapeNode 是否已被按下,特别是使用 LongPress 手势。请看下面的代码。知道出了什么问题,为什么我看不到“找到!”留言?

class Test: SKScene {
    let longPressGesture = UILongPressGestureRecognizer()

    override func didMove(to view: SKView) {

        longPressGesture.addTarget(self, action: #selector(GameScene.longPress))
        self.view?.addGestureRecognizer(longPressGesture)

        let testPath = UIBezierPath(rect: CGRect(x: (view.scene?.frame.midX)!, y: (view.scene?.frame.midY)!, width: 2 * 50.0, height: 2 * 50.0)).cgPath

        let testNode = Node.init(path: testPath, nodeName: "TEST")
        testNode.fillColor = UIColor.brown
        testNode.position = CGPoint(x: (view.scene?.frame.midX)!, y: (view.scene?.frame.midY)!)

        self.addChild(testNode)
    }

    func longPress(_ sender: UILongPressGestureRecognizer) {
        let longPressLocation = sender.location(in: self.view)

        if sender.state == .began {
            for child in self.children {
                if let shapeNode = child as? SKShapeNode {
                    if shapeNode.contains(longPressLocation) {
                        print("Found!")   
                    }
                }
            }
        } else if sender.state == .ended {
            print("ended")
        }
    }
}

非常感谢您的帮助!

【问题讨论】:

  • 我可能错了,但你正在做view.scene?.frame,而你可以做.frame :)

标签: swift sprite-kit uilongpressgesturerecogni


【解决方案1】:

您当前正在计算视图坐标系中的点击位置。为了在场景的坐标系中工作(因为SKShapeNode 已添加到场景中),您必须将点击位置从视图的坐标系转换为场景的坐标系,如下所示:

let longPressLocation = convertPoint(fromView: sender.location(in: self.view)) 

与原始问题无关,但要记住的一件好事是,在大多数情况下,强制展开并不是一个好主意(但有时它在开发阶段会有所帮助),并且您应该倾向于访问选项的底层值以安全的方式(例如使用 if let 语法)。

【讨论】:

  • 呃,总是强制解开.view。太烦人了。
  • ...这背后是有原因的,如果您正在过渡场景怎么办?强制展开会使您的应用崩溃
  • @Whirlwind,这完美地解决了我的问题。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-10
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
相关资源
最近更新 更多