swift 在SKSpriteNode上添加点击手势

njthzxwz  于 2023-04-19  发布在  Swift
关注(0)|答案(1)|浏览(147)

我想知道如何将点击手势识别器添加到SKSpriteNode中
我尝试在didMove方法上执行此操作,但似乎不起作用

wayang = SKSpriteNode(imageNamed: "WayangPlayGuy")
        wayang.size = CGSize(width: 200, height: 200)
        wayang.position = CGPoint(x: 87, y: 101)
        let wayangTap = UITapGestureRecognizer(target: self, action: #selector(didTapWayang))
        wayang.inputView?.addGestureRecognizer(wayangTap)
        //wayang.addGestureRecognizer(wayangTap)
        wayang.isUserInteractionEnabled = true
        addChild(wayang)
jjhzyzn0

jjhzyzn01#

对于iOS,您可以在您的场景中采用此方法SKScene

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        for child in children {
            if child.contains(touch.location(in: self)) {
                print(child)
                // child.somethingElse()
            }
        }
    }
}

与MacOS类似:(可以使用扩展来区分)

override func mouseDown(with event: NSEvent)

这是定位

event.location(in: self)

当然,强烈建议您存储一个引用,说明您想要检查哪些对象,或者区分它的类类型,或者更好地使用ECS对特定组件进行系统循环。

相关问题