如何检测孩子精灵的触摸

时间:2016-05-16 22:36:45

标签: ios swift cocoa-touch parent-child

我知道之前可能已经提出过这个问题,但没有任何内容符合我的要求。现在想象一下这种情况,我有一个游戏,在这个游戏中,屏幕中间有一个名为Background的SKSpriteNode。在那个背景精灵上有一个叫做Button的孩子。如何检测按钮上的触摸是否结束?如果有人可以帮我解决TouchesEnded功能的代码,也可以更详细地解释发生了什么。谢谢你,swift会很理想,但我想如果需要,我可以阅读Objective-C。

添加信息

这是我的两个精灵:

let buttonBackground = SKSpriteNode(imageNamed: "Button Background.png") //The parent node of button
let soundOn = SKSpriteNode(imageNamed: "Sound On.png") //The button being pressed, which is a child of buttonBackground

这是我的touchesEnded功能:

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    // Called when a touch begins

    for touch in touches {
        let location = touch.locationInNode(self)
        let nodeAtTouch = self.nodeAtPoint(location)
        let touchedSprite = nodeAtTouch as! SKSpriteNode

        if touchedSprite == button {
            print("YES")
        }
    }
}

1 个答案:

答案 0 :(得分:2)

触摸结束时,从该点获取节点

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
        let location = touch.locationInNode(self)
        let something = self.nodeAtPoint(location)
        let skNode = something as! SKSpriteNode
        //Do something with skNode
    }
}