如何检测 child 节点是否被触摸:Sprite Kit

How to detect if child node has been touched: Sprite Kit

我有一个 SKSpriteNode。这个SKSpriteNode有几个children。如何检测它是否被触摸?现在,让我说清楚,我已经知道在 SpriteKit 中设置一个按钮,我尝试使用与检测主 parent 节点是否被触摸相同的代码,但它没有用。该按钮不执行任何操作。有没有办法来解决这个问题?此外,我已经尝试将 child 节点的用户交互设置为 true。

你需要实现这个方法

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    print("Touched")
}

on class 关联到您要监视触摸事件的每个节点。所以你应该把这个方法添加到你的 main SKSpriteNode.

的每个后代

这是一种跟踪连续触摸(即方向箭头)的方法。

您需要在 SKScene 节点或父视图控制器中跟踪触摸:

var touches = Set<UITouch>()

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.touches.formUnion(touches)
    self.updateTouches()
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.touches.formUnion(touches)
    self.updateTouches()
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.touches.subtract(touches)
    self.updateTouches()
}

override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.touches.subtract(touches)
    self.updateTouches()
}

对于每次触摸,将坐标转换为相对于 SKNode。检查是否有任何触摸在 SKNode 的累积帧内。累积的帧是节点及其所有后代的总边界区域。

private func isTouching(node: SKNode) -> Bool {

    guard let parent = node.parent else {
        return false
    }

    let frame = node.calculateAccumulatedFrame()

    for touch in touches {

        let coordinate = touch.location(in: parent)

        if frame.contains(coordinate) {
            return true
        }
    }

    return false
}

例如:

override func update(_ currentTime: NSTimeInterval) {

    let touchingJump = isTouching(node: jumpButtonNode)

    if touchingJump {
        print("jump")
    }
}